关于c++ strncpy

来源:百度知道 编辑:UC知道 时间:2024/06/10 01:37:09
怎样可以让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;
/&

char* ch = "12345678";
"12345678"后还有个空字符
而strncpy(ch5,ch,5);只copy了ch前5个字符,即12345,没有空字符
因为strncpy本身就是为了替换掉字符串中的某一串字符,只是前面的替换成了12345
当用cout输出时,遇到空字符结束
在输出ch5时数组后面的都不是空字符(未初始化),所以输出乱码·直到遇到空字符为止(位置未定)··

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

分析下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'