使用带有字符指针的 strcat 函数

Ran*_*shi 5 c pointers string-literals strcat

我想通过使用两个字符指针来打印“Hello - World”,但我有一个“分段错误(核心转储)”问题。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define Hyphen " - "
int main()
{
  char* x="Hello";
  char* y="'World'";
  strcat(x, Hyphen);
  strcat(x, y);
  printf("%s",x);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 3

您本质上是在尝试使用字符串文字作为 的目标缓冲区strcat()。这是UB有两个原因

  • 您正在尝试修改字符串文字。
  • 您正在尝试写入超过分配的内存。

解决方案:您需要定义一个具有足够长度来容纳连接字符串的数组,并将其用作目标缓冲区。

通过更改代码的一种示例解决方案:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define Hyphen " - "
#define ARR_SIZE 32    // define a constant as array dimention

int main(void)              //correct signature
{
  char x[ARR_SIZE]="Hello";   //define an array, and initialize with "Hello"
  char* y="'World'";

  strcat(x, Hyphen);          // the destination has enough space
  strcat(x, y);               // now also the destination has enough space

  printf("%s",x);            // no problem.

  return 0;
}
Run Code Online (Sandbox Code Playgroud)