我试图弄清楚为什么 C 会这样做。这是一个非常简单的字符串连接代码,但根据进入 strcat 的内容,我得到了非常不同的输出。
有人可以对此有所了解吗?
// With all declared variables
char * hello = "HELLO";
char * world = "WORLD";
char * space = " ";
char * say_hello(){
char * out = "";
strcat(out,hello);
strcat(out,space);
strcat(out,world);
return out;
}
main(){
puts(say_hello());
}
// outputs "HELLO WORLD"
Run Code Online (Sandbox Code Playgroud)
// With all hello as declared variable
char * hello = "HELLO";
char * say_hello(){
char * out = "";
strcat(out,hello);
strcat(out," ");
strcat(out,"WORLD");
return out;
}
main(){
puts(say_hello());
}
// outputs "HELLOELLOLOELLO"
Run Code Online (Sandbox Code Playgroud)
// With all hello and world as declared variable
char * hello = "HELLO";
char * world = "WORLD";
char * say_hello(){
char * out = "";
strcat(out,hello);
strcat(out," ");
strcat(out,world);
return out;
}
main(){
puts(say_hello());
}
// outputs "HELLOELLOWORLD"
Run Code Online (Sandbox Code Playgroud)
// With all constants
char * say_hello(){
char * out = "";
strcat(out,"HELLO");
strcat(out," ");
strcat(out,"WORLD");
return out;
}
main(){
puts(say_hello());
}
// outputs "HELLO WORLD"
Run Code Online (Sandbox Code Playgroud)
所有的代码都是无效和危险的。
首先,禁止修改字符串文字,并尝试这样做会调用未定义的行为。strcat将修改作为第一个参数传递的字符串,因此您不能在那里传递字符串文字(或指向字符串文字的指针)。
其次,""是单元素数组{'\0'}。它无法存储由连接创建的字符串。您必须分配足够的空间。
请注意,非静态局部数组的生命期在从函数返回时结束,因此您必须动态或静态分配。
动态分配:
#include <stdlib.h>
char * say_hello(){
char * out = calloc(32, sizeof(*out)); /* allocate */
if (out == NULL) exit(1); /* check if allocation succeeded */
strcat(out,hello);
strcat(out,space);
strcat(out,world);
return out;
}
Run Code Online (Sandbox Code Playgroud)
静态分配(警告:这不是线程安全的):
char * say_hello(){
static char out[32];
out[0] = '\0';
strcat(out,hello);
strcat(out,space);
strcat(out,world);
return out;
}
Run Code Online (Sandbox Code Playgroud)