如何不使用strncat函数合并两个字符数组?代码异常求排查
问题分析与修复
你的代码存在三个关键问题,逐一修正即可正常运行:
1. 第二个循环的索引偏移错误
第二个for循环里,你写了result[k+1+count1] = text2[k];,多了一个不必要的+1。text1的长度为count1,它的最后一个字符位于索引count1-1的位置,因此text2应该从索引count1开始填充,正确写法是:
for(int k = 0; k<count2; k++) { result[k + count1] = text2[k]; }
2. 未添加字符串结束符
C语言的字符串必须以'\0'结尾,否则后续读取或打印操作会访问到内存中的垃圾数据。在填充完两个字符数组后,需要手动添加结束符:
result[count1 + count2] = '\0';
3. 打印单个字符时使用了错误格式符
最后一个for循环里,你用%s格式符打印result[j],但result[j]是单个字符,%s是用于打印字符串的,会把字符的ASCII值当作内存地址访问,引发错误。应改用%c格式符:
for(int j = 0; j<count1+count2; j++) { printf("%c", result[j]); }
修复后的完整代码
#include <stdio.h> #include <string.h> // 必须包含strlen依赖的头文件,否则编译可能出现警告 int main() { char text1[] = {"Hello"}; char text2[] = {", how are you?"}; char result[100]; int count1 = strlen(text1); int count2 = strlen(text2); printf("%d\n", count1); printf("%d\n", count2); for(int i = 0; i<count1; i++) { result[i] = text1[i]; } for(int k = 0; k<count2; k++) { result[k + count1] = text2[k]; } result[count1 + count2] = '\0'; // 添加字符串结束符 // 直接打印整个字符串更简洁,无需循环逐个输出 printf("%s\n", result); return 0; }
内容的提问来源于stack exchange,提问作者Valen7ino
相关产品推荐
相关产品推荐

