常数C字符串拼接 [英] C string concatenation of constants
问题描述
答案之一来为什么你不为你的web应用程序用C ?包含以下内容:
对于下面的C废话例如:
为const char *富=富;
为const char *巴=酒吧;
字符* foobar的=(的char *)malloc的(strlen的(富)+ strlen的(巴)+1);
的strcpy(FOOBAR,富);
strcat的(FOOBAR,富);
其实,常量可以而且应该自然地用C串联:
为const char为foo [] =富;
为const char酒吧[] =酒吧;
CHAR foobar的[] = foo的酒吧; //看马,我这样做是没有任何运营商!和使用[]而不是*,甚至让你修改字符串,或者发现其长度:
INT foo_str_len = sizeof的(FOOBAR)-1;
所以,请你(错误地)声称在此之前,C是很难用字符串使用,学会如何用C
块引用>我尝试过自己,但得到一个错误:
料','或';'字符串常量前
块引用>所以我的问题是:我要告诉,以使这项工作的编译器的东西或者是上面的帖子根本就是错误的?请注意,我所知道的其他方式来连接使用C字符数组。
解决方案
(字符*)malloc的
块引用>从不强制转换的malloc的结果C.阅读这和<一个href=\"http://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc\">this.
其实,常量可以而且应该自然地用C串联
块引用>没有,的字符串的可以而且应该在C串联
foo的
是一个字符串文字,常量字符富[]
是一个常量字符串(字符数组)。在code富,酒吧
将自动连接起来时,code富栏
不会如果你愿意,你可以隐藏宏后面的字符串:
的#define富富
#定义栏栏
CHAR foobar的[] = foo的酒吧; //实际工作
所以,请你(错误地)声称在此之前,C是很难用字符串使用,学会如何用C
块引用>C 是的相当困难用绳子用,因为我们可以从这个例子中看到。尽管他们的傲慢自信,谁写它的人混在一起的各种概念,仍然需要学习如何用C
One of the answers to Why do you not use C for your web apps? contains the following:
For the C crap example below:
const char* foo = "foo"; const char* bar = "bar"; char* foobar = (char*)malloc(strlen(foo)+strlen(bar)+1); strcpy(foobar, foo); strcat(foobar, foo);
Actually, constants CAN AND SHOULD be concatenated naturally in C:
const char foo[] = "foo"; const char bar[] = "bar"; char foobar[] = foo bar; // look Ma, I did it without any operator!
And using [] instead of * will even let you modify the string, or find their length:
int foo_str_len = sizeof(foobar)-1;
So, PLEASE, before you (falsely) claim that C is difficult to use with strings, learn how to use C.
I've tried it myself but get an error:
expected ‘,’ or ‘;’ before string constant
So my question is: Do I need to tell the compiler something in order to make this work or is the above post simply wrong? Please note that I'm aware of other ways to concatenate character arrays in C.
解决方案(char*)malloc
Never typecast the result of malloc in C. Read this and this.
Actually, constants CAN AND SHOULD be concatenated naturally in C
No, string literals can and should be concatenated in C.
"foo"
is a string literal andconst char foo[]
is a constant string (array of characters). The code"foo" "bar"
will concatenate automatically, the codefoo bar
will not.If you want, you can hide the string literals behind macros:
#define foo "foo" #define bar "bar" char foobar[] = foo bar; // actually works
So, PLEASE, before you (falsely) claim that C is difficult to use with strings, learn how to use C.
C is rather difficult to use with strings, as we can see from this very example. Despite their arrogant confidence, the person who wrote it mixed up the various concepts and still has to learn how to use C.
这篇关于常数C字符串拼接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!