如何在C中连接字符串?

Hak*_*kan 0 c string string-concatenation

如何以这种方式连接字符串?

例如:

char *txt = "Hello";
txt=txt+"World!";
Run Code Online (Sandbox Code Playgroud)

我尝试过,但事实并非如此.

Gop*_*opi 5

txt 是指针,应该为它分配内存.

有以下检查是好的

  1. 需要分配的内存量可以通过计算

    size_t size = strlen("Hello") + strlen("World");

  2. char *txt = malloc(size + 1);

  3. 在访问malloc()之前检查它的返回值.

    if(txt != NULL)

动态地这可以做到:

 char *txt = malloc(size+1); /* Number of bytes needed to store your strings */
 strcpy(txt,"Hello");
 strcat(txt,"World");
Run Code Online (Sandbox Code Playgroud)

使用它之后应该释放分配的内存

free(txt);
Run Code Online (Sandbox Code Playgroud)

或者你也可以

char txt[30];
strcpy(txt,"Hello");
strcat(txt,"World");
Run Code Online (Sandbox Code Playgroud)