它什么也没打印。我认为问题出在 char * 类型上,但我不知道是否以及为什么。
int main() {
char *a = "0123456789" ;
char *b = "abcdefghij" ;
strcat (a,b) ;
printf( "%s", a ) ;
}
最佳答案
strcat
修改destination
参数缓冲区 but a
's buffer is in read-only memory as it's a string literal 。
解决方案是在运行时创建一个缓冲区并将其用作缓冲区。当然,您需要先将 a
复制到其中。
char* a = "1234567890";
char* b = "abcdefghij";
size_t aLen = strlen( a );
char* combined = malloc( sizeof(char) * ( strlen(a) + strlen(b) + 1 ) );
strcpy_s( combined, aLen, a ); // always use _s versions of string/buffer functions!
strcat( combined, b );
puts( combined );
free( combined );
或者,在 C99 中,我们可以只使用预先初始化的堆栈分配数组(并且预先分配得足够大)。堆栈数组,包括预初始化的数组,可以将其缓冲区写入:
char a[100] = "1234567890";
strcat( a, "abcdefghij" );
puts( a );
关于char * 、 strcat 交互。为什么它不打印任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50689304/