尝试将字符附加到字符数组

我正在尝试将字符“t”附加到值为“hello”的字符数组中,我正在确定数组大小,创建一个大于1个字符的新数组,分配新的字符和’\ 0’作为最后两个角色。 我不断打印旧值(你好)。 谢谢

#include  #include  void append(char * string,char ch) { int size; for (size=0;size<255;size++) { if (string[size]=='\0') break; } char temp[size+2]; strcpy(temp,string); temp[size+1]='t'; temp[size+2]='\0'; printf("the test string is: %s\n",temp); } int main() { char test[]="hello"; append(&test,'t'); return 0; } 

首先,你的函数调用是错误的。 它应该是

 append(test,'t'); // When an argument to a function, array decay to pointer to its first element. 

然后,您必须从前一个字符串中删除'\0' ,否则您将获得相同的字符串。 这是因为在追加字符ch ,新字符串看起来像

 "hello\0t\0" 

注意t之前的'\0'printf将停在该null字符处。

您可以使用字符't'覆盖'\0'字符

 temp[size] = ch; temp[size+1] = '\0'; 

注意:由于对语句中数组temp的绑定访问,您的程序会调用未定义的行为

  temp[size+2]='\0'; 

有效的function可以通过以下方式查看

 void append( const char *string, char ch ) { size_t size = 0; while ( string[size] ) ++size; char temp[size+2]; strcpy( temp, string ); temp[size++] = ch; temp[size++] ='\0'; printf( "the test string is: %s\n", temp ); } 

它必须被称为

 append( test, 't' ); 

由于每当string[size]=='\0'时循环都会中断,然后将一个字符串复制到temptemp[size]也是\0 ,它永远不会被覆盖,因为分配的下一个字符size+1 。 所以你的温度总是以size终止。 最后temp"hello\0t\0"

您找到但永远不会覆盖第一个空字符。