用strncpy时字符数组和字符指针有着怎样的区别?#include <iostream>using std::cout;using std::endl;int main(){char ch1[5];char* ch2;char* ch3 = "12345678";strncpy(ch1,ch3,5);//ch1输出结果:12345&^% (注:后面几个是乱码)strncpy(ch3,ch2,5);//ch3输出结果:12345cout << ch1 <<endl; cout << ch3 <<endl; return 0;}能解释一下strncpy的运行结果么??int main(){char ch1[5],ch5[5];char ch2[11],ch6[11];char* ch3 = new char[6];char* ch7 = new char[6];char* ch4 = new char[11];char* ch8 = new char[11];char* ch9 = new char[6];char* ch = "12345678";//strcpy(ch1,ch); cout << 1 << ch1 << endl;//strcpy(ch2,ch); cout << 2 << ch2 << endl;//strcpy(ch3,ch); cout << 3 << ch3 << endl;//strcpy(ch4,ch); cout << 4 << ch4 << endl; //上面四行结果均是12345678strncpy(ch5,ch,5); cout << 5 << ch5 << endl; //512345后面乱码strncpy(ch6,ch,5); cout << 6 << ch6 << endl; //612345后面乱码strncpy(ch7,ch,5); cout << 7 << ch7 << endl; //712345后乱码strncpy(ch7,ch,6); cout << 7 << ch7 << endl; //7123456后乱码strncpy(ch8,ch,5); cout << 8 << ch8 << endl; //812345后面乱码strncpy(ch9,ch,5); cout << 9 << ch9 << endl; //912345后面乱码system("pause");return 0;}
2 回答
大话西游666
TA贡献1817条经验 获得超14个赞
操作字串时,不要忘了给最后的'\0'分配空间,不然输出时就会带着乱码,正确的做法是:
char *ch2 = new char[6];
strncpy(ch2, ch3, 5);
ch2[5] = '\0';
cout << ch2 << endl;
不能少了这句
delete[] ch2;
之所以出现乱码,是因为执行strncpy的过程中并没有将字串结束符'\0'赋值给目标,目标字串没有结束符输出时自然就不知道应该什么时候停止输出,除非遇到'\0'字符,因此你会看到乱码,就这样。
慕的地10843
TA贡献1785条经验 获得超8个赞
分析下strncpy的源代码应该就明白了 ,库函数并没有对dest检查,有可能dest不是以'\0'结尾, 输出的时候就会出错了
char * __cdecl strncpy (
char * dest,
const char * source,
size_t count
)
{
char *start = dest;
while (count && (*dest++ = *source++)) /* copy string */
count--;
if (count) /* pad out with zeroes */
while (--count)
*dest++ = '\0';
return(start);
}
- 2 回答
- 0 关注
- 68 浏览
添加回答
举报
0/150
提交
取消