c - 使用带有 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;
}
解决方案
您实际上是在尝试使用字符串文字作为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;
}
推荐阅读
- python - 使用 python osmnx 模块时出错,无法绘制足迹和 streetnetwork
- wix - 自定义操作不会在 WIX 安装程序中运行
- php - 单击电子邮件中的 Outlook 安全链接保护链接似乎执行了两次代码
- swiftui - 使用滑块更新 SWIFTUI 文本字体大小?
- java - 如何在spring mvc中为图像定义getter和setter
- c# - 您如何在 Xamarin 中拥有独特的 ListView 元素,同时还使用 RecycleElement?
- python - python request.get 总是抛出状态码 200
- android - Flutter - CircularProgressIndicator 始终运行
- c# - 为什么 .NET Web API JSON 响应有效负载中的长类型在 16 位后四舍五入?
- google-maps - Flutter 在地图上设置折线失败