C++ strncpy函数异常输出求助:预期3个输出却得7个
分析strncpy导致输出异常的问题
嘿,我来帮你拆解下你遇到的这个问题!你说用strncpy时预期3个输出但实际得到7个,核心问题出在对strncpy的特性理解和代码里的终止符错误上。
先看你提供的代码片段(我帮你补全了未写完的部分以便分析):
char x[] = "just see that."; char y[15]; char z[10]; char l[14]; strcpy(y, x); cout << "The string in array x is: " << x << "\n The string in array y is: " << y << '\n'; strncpy(z, x, 9); z[9] = '\n'; cout << "The string in array z is: " << z << endl; strncpy(l, x, 13); l[13] = '\n'; cout << "The string in array l is: " << l << endl;
strncpy的特性问题:这个函数不会自动在目标数组末尾添加字符串终止符'\0'。如果源字符串的长度大于等于你指定的复制长度(比如你给z复制9个字符,源字符串x的长度远大于9),目标数组z里就没有'\0',而cout输出字符串时会一直读取内存,直到找到第一个'\0',这就导致了额外的乱码输出。- 错误的终止符设置:你把
z[9]和l[13]设成了'\n',这只是换行符,不是字符串结束符。cout根本不把它当终止信号,自然会继续读后面的内存内容。
修复方案
复制完成后,手动给目标数组添加正确的字符串终止符'\0',同时要确保数组有足够的空间容纳这个终止符:
char x[] = "just see that."; char y[15]; char z[10]; char l[14]; strcpy(y, x); cout << "The string in array x is: " << x << "\n The string in array y is: " << y << '\n'; // 修复z数组的处理 strncpy(z, x, 9); z[9] = '\0'; // 替换成字符串终止符 cout << "The string in array z is: " << z << endl; // 修复l数组的处理 strncpy(l, x, 13); l[13] = '\0'; // 替换成字符串终止符 cout << "The string in array l is: " << l << endl;
这样修改后,cout就能正确识别字符串的结束位置,输出你预期的内容了。
内容的提问来源于stack exchange,提问作者Shawn
相关产品推荐
相关产品推荐

