Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

c - 如何在C中连接const / literal字符串?(How do I concatenate const/literal strings in C?)

I'm working in C, and I have to concatenate a few things.

(我正在C语言中工作,我必须串联一些东西。)

Right now I have this:

(现在我有这个:)

message = strcat("TEXT ", var);

message2 = strcat(strcat("TEXT ", foo), strcat(" TEXT ", bar));

Now if you have experience in C I'm sure you realize that this gives you a segmentation fault when you try to run it.

(现在,如果您有C方面的经验,我相信您会在尝试运行它时遇到分段错误。)

So how do I work around that?

(那么我该如何解决呢?)

  ask by The.Anti.9 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In C, "strings" are just plain char arrays.

(在C语言中,“字符串”只是纯char数组。)

Therefore, you can't directly concatenate them with other "strings".

(因此,您不能将它们与其他“字符串”直接连接。)

You can use the strcat function, which appends the string pointed to by src to the end of the string pointed to by dest :

(您可以使用strcat函数,它将src指向的字符串附加到dest指向的字符串的末尾:)

char *strcat(char *dest, const char *src);

Here is an example from cplusplus.com :

(这是来自cplusplus.com示例 :)

char str[80];
strcpy(str, "these ");
strcat(str, "strings ");
strcat(str, "are ");
strcat(str, "concatenated.");

For the first parameter, you need to provide the destination buffer itself.

(对于第一个参数,您需要提供目标缓冲区本身。)

The destination buffer must be a char array buffer.

(目标缓冲区必须是char数组缓冲区。)

Eg: char buffer[1024];

(例如: char buffer[1024];)

Make sure that the first parameter has enough space to store what you're trying to copy into it.

(确保第一个参数有足够的空间来存储您要复制到其中的内容。)

If available to you, it is safer to use functions like: strcpy_s and strcat_s where you explicitly have to specify the size of the destination buffer.

(如果可以使用,则使用诸如strcpy_sstrcat_s类的函数strcpy_s安全,在这些函数中,您必须明确指定目标缓冲区的大小。)

Note : A string literal cannot be used as a buffer, since it is a constant.

(注意 :字符串文字不能用作缓冲区,因为它是一个常量。)

Thus, you always have to allocate a char array for the buffer.

(因此,您始终必须为缓冲区分配一个char数组。)

The return value of strcat can simply be ignored, it merely returns the same pointer as was passed in as the first argument.

(可以简单地忽略strcat的返回值,它仅返回与作为第一个参数传入的指针相同的指针。)

It is there for convenience, and allows you to chain the calls into one line of code:

(它在那里是为了方便起见,它允许您将调用链接到一行代码中:)

strcat(strcat(str, foo), bar);

So your problem could be solved as follows:

(因此,您的问题可以通过以下方式解决:)

char *foo = "foo";
char *bar = "bar";
char str[80];
strcpy(str, "TEXT ");
strcat(str, foo);
strcat(str, bar);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...