char数组的不同赋值方法

  • 本文关键字:赋值 方法 数组 char c
  • 更新时间 :
  • 英文 :


有人能指出这段代码出了什么问题吗?为什么第一个打印案例不起作用,而第二个不起作用?谢谢

char source[] = "hello folks";
char destination[11];
strcpy(destination, source);
for(int i = 0; source[i]; i++) {
printf("%c" , source[i]); 
}
printf("n");
for(int i = 0; destination[i]; i++) {
printf("%c" , destination[i]); 
}
printf("n");

您将destination声明为一个由11个字符组成的数组,但随后使用strcpysource中的12个字符复制到其中。每个字符串都需要有一个NUL终止符,它是字符串的一部分,因此在计算容纳字符串所需的数组大小时对其进行计数很重要。

最新更新