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

现在我有这个:

message = strcat("TEXT ", var);

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

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


当前回答

如果你有C语言的经验,你会注意到字符串只是字符数组,其中最后一个字符是空字符。

现在这是相当不方便的,因为你必须找到最后一个字符,以追加一些东西。Strcat会帮你的。

所以strcat通过第一个参数搜索空字符。然后它将用第二个参数的内容替换它(直到它以null结束)。

现在让我们看一下你的代码:

message = strcat("TEXT " + var);

在这里,您向指向文本“text”的指针添加了一些内容(“text”的类型是const char*。一个指针)。

这通常是行不通的。此外,修改“TEXT”数组也将不起作用,因为它通常被放置在常量段中。

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

这可能会工作得更好,除非您再次尝试修改静态文本。Strcat没有为结果分配新的内存。

我建议这样做:

sprintf(message2, "TEXT %s TEXT %s", foo, bar);

阅读sprintf的文档,检查它的选项。

现在有一点很重要:

确保缓冲区有足够的空间容纳文本和空字符。有几个函数可以帮助您,例如strncat和printf的特殊版本,它们为您分配缓冲区。 不确保缓冲区大小将导致内存损坏和可远程利用的错误。

其他回答

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

char bigEnough[64] = "";

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

/* and so on */

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

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

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

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

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

具体地说:

剪断…

目的地

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

这里也有一个例子。

另外,如果您不知道要连接多少字符串,malloc和realloc也很有用。

#include <stdio.h>
#include <string.h>

void example(const char *header, const char **words, size_t num_words)
{
    size_t message_len = strlen(header) + 1; /* + 1 for terminating NULL */
    char *message = (char*) malloc(message_len);
    strncat(message, header, message_len);

    for(int i = 0; i < num_words; ++i)
    {
       message_len += 1 + strlen(words[i]); /* 1 + for separator ';' */
       message = (char*) realloc(message, message_len);
       strncat(strncat(message, ";", message_len), words[i], message_len);
    }

    puts(message);

    free(message);
}

试试类似的方法:

#include <stdio.h>
#include <string.h>

int main(int argc, const char * argv[])
{
  // Insert code here...
  char firstname[100], secondname[100];
  printf("Enter First Name: ");
  fgets(firstname, 100, stdin);
  printf("Enter Second Name: ");
  fgets(secondname,100,stdin);
  firstname[strlen(firstname)-1]= '\0';
  printf("fullname is %s %s", firstname, secondname);

  return 0;
}