我想使用两个字符指针打印“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;
}
您实质上是在尝试使用字符串文字作为 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;
}