我在用C语言工作,我必须把一些东西连接起来。

现在我有这个:

message = strcat("TEXT ", var);

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

现在,如果你有C语言的经验,我相信你会意识到,当你试图运行它时,这会给你一个分割错误。我该怎么做呢?


当前回答

字符串也可以在编译时进行连接。

#define SCHEMA "test"
#define TABLE  "data"

const char *table = SCHEMA "." TABLE ; // note no + or . or anything
const char *qry =               // include comments in a string
    " SELECT * "                // get all fields
    " FROM " SCHEMA "." TABLE   /* the table */
    " WHERE x = 1 "             /* the filter */ 
                ;

其他回答

strcat()的第一个参数需要能够为连接的字符串保留足够的空间。因此,分配一个缓冲区,使其具有足够的空间来接收结果。

char bigEnough[64] = "";

strcat(bigEnough, "TEXT");
strcat(bigEnough, foo);

/* and so on */

Strcat()将第二个参数与第一个参数连接起来,并将结果存储在第一个参数中,返回的char*就是第一个参数,只是为了方便。

您不会得到一个连接第一个和第二个参数的新分配字符串,我猜这是您根据代码所期望的。

您正在尝试将字符串复制到静态分配的地址中。你需要进入缓冲地带。

具体地说:

剪断…

目的地

Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.

剪断…

http://www.cplusplus.com/reference/clibrary/cstring/strcat.html

这里也有一个例子。

不要忘记初始化输出缓冲区。strcat的第一个参数必须是一个空结束的字符串,并为结果字符串分配足够的额外空间:

char out[1024] = ""; // must be initialized
strcat( out, null_terminated_string ); 
// null_terminated_string has less than 1023 chars

避免在C代码中使用strcat。最干净,也是最重要的,最安全的方法是使用snprintf:

char buf[256];
snprintf(buf, sizeof(buf), "%s%s%s%s", str1, str2, str3, str4);

一些评论者提出了一个问题,即参数的数量可能与格式字符串不匹配,代码仍然会被编译,但如果出现这种情况,大多数编译器已经发出警告。

这就是我的解

#include <stdlib.h>
#include <stdarg.h>

char *strconcat(int num_args, ...) {
    int strsize = 0;
    va_list ap;
    va_start(ap, num_args);
    for (int i = 0; i < num_args; i++) 
        strsize += strlen(va_arg(ap, char*));

    char *res = malloc(strsize+1);
    strsize = 0;
    va_start(ap, num_args);
    for (int i = 0; i < num_args; i++) {
        char *s = va_arg(ap, char*);
        strcpy(res+strsize, s);
        strsize += strlen(s);
    }
    va_end(ap);
    res[strsize] = '\0';

    return res;
}

但是你需要指定你要连接多少个字符串

char *str = strconcat(3, "testing ", "this ", "thing");