我正在尝试将字符 't' 附加到值为“hello”的字符数组,我正在确定数组大小,创建一个大 1 个字符的新数组,分配新的字符和 '\0' 作为最后两个字符。 我一直在打印旧值(你好)。谢谢
#include <string.h>
#include <stdio.h>
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;
}
最佳答案
一个有效的函数可以如下所示
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' );
关于c - 尝试将字符附加到字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31214287/