c 中strcpy的问题

来源:百度知道 编辑:UC知道 时间:2024/06/17 14:58:32
void main(void)
{
char *str;// =NULL;

str = (char *)malloc(50);

strcpy(str,"hello");
strcpy(str+7,"hello world");
printf("%s",str);
free(str);
}
该函数为什么只打印出hello?

printf()函数在输出字符数组时,只输出\0之前的字符,而由于strcpy(str,"hello"); 的作用,导致str[5]=='\0',而strcpy(str+7,"hello world"); 又没有改变str[5]的内容,所以只输出前5个字符,即字符串"hello"

#include <string>
#include <iostream>
void main(void)
{
char *str;// =NULL;

str = (char *)malloc(50);

strcpy(str,"hello");
printf("1111\n%s\n",str);
strcpy(str+5,"hello world");
printf("2222\n%s\n",str);
free(str);
}

因为你不会数数