You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:37:39