【发布时间】:2021-09-22 21:24:29
【问题描述】:
我正在做一些结构练习,但我无法理解分段错误。 我已经完成了几乎所有事情,分段错误在循环 for(i = 0;i
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<stdint.h>
#define MAX 50
int main(void)
{
typedef struct {
char *name;
char *l_name;
u_int32_t age;
}person;
u_int32_t i;
person p[2];
p->name = (char *) malloc(sizeof(char) * MAX);
p->l_name = (char *) malloc(sizeof(char)* MAX);
if(p->name == NULL || p->l_name == NULL){
fprintf(stderr,"Error allocating memory");
exit(1);
}
for(i = 0;i<2;i++){
if(!fgets(p[i].name,sizeof(p[i].name),stdin)){
fprintf(stderr,"Error reading string");
exit(2);
}
if(!fgets(p[i].l_name,sizeof(p[i].l_name),stdin)){
fprintf(stderr,"Error reading string");
exit(3);
}
}
}
【问题讨论】:
-
你认为
p[1].name和p[1].l_name指向什么? -
victor 0x3E7,
sizeof(p[i].name)可能是 4 或 8,而不是 50。 -
@chux-ReinstateMonica 为什么是 4 或 8 而不是 50?
-
p->name与p[0].name相同。所以你为第一个人的名字分配了内存,但你从来没有为第二个人分配任何东西。 -
@victor0x3E7 最好的。取决于编码目标。简单的修复,尝试
fgets(p[i].name, MAX ,stdin)并分配给p[1].name等。
标签: c for-loop segmentation-fault initialization dynamic-memory-allocation