首页 > 解决方案 > 使用带有 char 指针的 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;
}

标签: cpointersstring-literalsstrcat

解决方案


您实际上是在尝试使用字符串文字作为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;
}

推荐阅读