c - 将 malloc 与 char 指针一起使用时出现段错误

标签 c pointers char segmentation-fault malloc

我是 C 和学习结构的新手。我正在尝试 malloc 一个大小为 30 的字符指针,但它给出了一个段错误(核心转储)。我在互联网上搜索过它,但无法解决这个问题。任何帮助将不胜感激。
可能我错误地访问了结构的 char* 成员?

typedef struct{
int x;
int y;
char *f;
char *l;
}str;

void create_mall();

void create_mall() //Malloc the struct
{
str *p;
p->f = (char*)malloc(sizeof(char)*30);  // segmentation fault here
p->l = (char*)malloc(sizeof(char)*30);
printf("Enter the user ID:");
scanf("%d",&p->x);
printf("\nEnter the phone number:");
scanf("%d",&p->y);
printf("\nEnter the First name:");
scanf("%29s",p->f);
printf("\nEnter the Last name:");
scanf("%29s",p->l);
printf("\nEntered values are: %d %d %s %s\n",p->x,p->y,p->f,p->l);
}

int main(void)
{
create_mall();
return 0;
}

最佳答案

这是你的问题:

str *p;

你已经声明了一个指向 str 实例的指针,但是你还没有用一个值初始化它。您要么需要将此变量移动到堆栈:

str p;

...或malloc 先为它分配一些内存:

str *p = (str*)malloc(sizeof(str));

关于c - 将 malloc 与 char 指针一起使用时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12947419/

相关文章:

c - 为什么C在调用汇编函数时不将指针压入堆栈?

c - 获取文本文件的每个元素,直到“:”并存储在struct变量中

c - C 中传递指针

pointers - Golang返回指向接口(interface)的指针抛出错误

c - 用 ANSI C 编写的套接字客户端和套接字服务器中的字符数组

c - 如何使用 CCS 检测 16 位溢出

c - Linux : When sending Ethernet frames the ethertype is being re-written

c - 使用指针将节点插入二叉树

C-Compiler 在将字符串分配给 char 数组时说 "Cannot convert char * to char"

delphi - 两个字符串/集合的交集