如何在 C 中连接常量/文字字符串? [英] How do I concatenate const/literal strings in C?

查看:43
本文介绍了如何在 C 中连接常量/文字字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用 C 语言工作,我必须连接一些东西.

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

现在我有这个:

message = strcat("TEXT ", var);

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

现在,如果您有 C 方面的经验,我相信您会意识到当您尝试运行它时,这会给您带来分段错误.那么我该如何解决这个问题?

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. So how do I work around that?

推荐答案

在 C 中,字符串"只是普通的 char 数组.因此,您不能直接将它们与其他字符串"连接起来.

In C, "strings" are just plain char arrays. Therefore, you can't directly concatenate them with other "strings".

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

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

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

这是一个 来自 cplusplus.com 的示例:

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

对于第一个参数,您需要提供目标缓冲区本身.目标缓冲区必须是字符数组缓冲区.例如:char buffer[1024];

For the first parameter, you need to provide the destination buffer itself. The destination buffer must be a char array buffer. E.g.: char buffer[1024];

确保第一个参数有足够的空间来存储您要复制到其中的内容.如果您可以使用,使用诸如 strcpy_sstrcat_s 之类的函数会更安全,其中您必须明确指定目标缓冲区的大小.

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.

注意:字符串文字不能用作缓冲区,因为它是一个常量.因此,您总是必须为缓冲区分配一个字符数组.

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.

strcat 的返回值可以简单地忽略,它只返回作为第一个参数传入的相同指针.它的存在是为了方便,并允许您将调用链接到一行代码中:

The return value of strcat can simply be ignored, it merely returns the same pointer as was passed in as the first argument. 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);

这篇关于如何在 C 中连接常量/文字字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆