【发布时间】:2017-01-11 17:40:14
【问题描述】:
我有以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test {
char *str;
};
int main(void)
{
struct test *p = malloc(sizeof(struct test));
p->str = "hello world";
printf("%s\n",p->str);
return 0;
}
它工作正常。但是当我这样写的时候:
struct test *p = malloc(sizeof(struct test));
p->str="hello";
strcat(p->str," world");
或者这个:
struct test *p = malloc(sizeof(struct test));
strcat(p->str,"hello world");
我遇到了分段错误。
我在这里找到了一些相关的解释:
您只为结构本身分配内存。这包括指向 char 的指针,它在 32 位系统上只有 4 个字节,因为它是结构的一部分。它不包括未知长度字符串的内存,因此如果您想要一个字符串,您也必须手动为其分配内存
Allocate memory for a struct with a character pointer in C
通过解释,我知道如果我想使用strcat,正确的代码应该是这样的:
struct test *p = malloc(sizeof(struct test));
p->str = malloc(size);
strcat(p->str,"hello world");
所以我的问题是为什么 p->str = "hello world" 不需要分配内存但 strcat(p->str,"hello world") 需要在使用前分配内存?
我的编译器是“gcc (Debian 4.9.2-10) 4.9.2”。我的英语很基础,请不要介意:)
【问题讨论】:
-
您的“正确代码”也不正确,您还需要在调用 strcat 之前初始化为空字符串
-
strcat()只能用于将更多文本附加到已经初始化的字符串,分配内存后不能立即使用。首先使用strcpy(),或者至少确保将字符串的第一个元素设置为\0,使其成为有效的空字符串。
标签: c