如何连接常量/文字字符串使用C? [英] How to concatenate const/literal strings in C?

查看:151
本文介绍了如何连接常量/文字字符串使用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,串只是普通的字符阵列。因此,你不能直接与其他弦将它们连接起来。

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例如href=\"http://www.cplusplus.com/reference/clibrary/cstring/strcat.html\">:

Here is an example from cplusplus.com:

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

对于第一个参数,您需要提供目标缓冲区本身。目标缓冲区必须是一个字符数组缓冲区。例如:字符缓冲区[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.

注意的:字符串文字不能被用作缓冲,因为它是一个常数。因此,你总是要为分配缓冲区中的字符数组。

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的的返回值可以简单地被忽略,因为传递中作为第一个参数它只返回相同的指针。这是有便利,并允许您链的调用到code的一行:

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天全站免登陆