c - C中连接变量和常量之间的区别
问题描述
我试图弄清楚为什么 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"
// 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"
// 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"
// 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"
解决方案
所有代码都是无效且危险的。
首先,禁止修改字符串文字,并且尝试这样做会调用未定义的行为。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;
}
静态分配(警告:这不是线程安全的):
char * say_hello(){
static char out[32];
out[0] = '\0';
strcat(out,hello);
strcat(out,space);
strcat(out,world);
return out;
}
推荐阅读
- java - 如何从 .class 文件生成 C(本机)头文件(已编译)
- javascript - 当我向下滚动页面时,Particles.js 不会继续 - HTML
- python - pytorch,如何制作相同大小的张量模型(x)和答案(x)?
- python - 如何使用 utf-8 编码制作 lxml 输出文件
- nix - 配置 ~/.config/nixpkgs/config.nix 的位置
- php - curl 不在实时服务器中工作,但在 localhost 中运行
- python - 如何在 Python 中将 x 轴范围从 1 到 20,每个差异有 5 个?
- angular - 分配外部指令属性的角度语法?
- ionic-framework - Ionic SQLite 插件在删除时总是抛出异常
- php - 如何显示总数 年龄组