怎样可以让ch1也是12345呢?

用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输出结果:12345
cout << 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; //上面四行结果均是12345678
strncpy(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;
}





泛舟湖上清波郎朗
浏览 69回答 2
2回答

大话西游666

操作字串时,不要忘了给最后的'\0'分配空间,不然输出时就会带着乱码,正确的做法是:char *ch2 = new char[6];strncpy(ch2, ch3, 5);ch2[5] = '\0';cout << ch2 << endl;不能少了这句delete[] ch2;之所以出现乱码,是因为执行strncpy的过程中并没有将字串结束符'\0'赋值给目标,目标字串没有结束符输出时自然就不知道应该什么时候停止输出,除非遇到'\0'字符,因此你会看到乱码,就这样。

慕的地10843

分析下strncpy的源代码应该就明白了 ,库函数并没有对dest检查,有可能dest不是以'\0'结尾, 输出的时候就会出错了&nbsp;char * __cdecl strncpy (&nbsp;char * dest,&nbsp;const char * source,&nbsp;size_t count&nbsp;)&nbsp;{&nbsp;char *start = dest;&nbsp;while (count && (*dest++ = *source++)) /* copy string */&nbsp;count--;&nbsp;if (count) /* pad out with zeroes */&nbsp;while (--count)&nbsp;*dest++ = '\0';&nbsp;return(start);&nbsp;}&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP