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

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

问题描述

我正在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方面的经验,我相信您会意识到,这在遇到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数组缓冲区。例如: 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_s strcat_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.

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

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中连接const / literal字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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