【发布时间】:2020-12-12 06:21:22
【问题描述】:
我正在尝试学习嵌套结构。当我使用结构变量访问它时,它工作正常。 但是当我尝试使用指针访问它时,它会显示分段错误。
#include <stdio.h>
#include <stdlib.h>
struct Vehicle {
int eng;
int weight;
};
struct Driver {
int id;
float rating;
struct Vehicle v;
};
void main() {
struct Driver *d1;
d1->id = 123456;
d1->rating = 4.9;
d1->v.eng = 456789;
printf("%d\n", d1->id);
printf("%f\n", d1->rating);
printf("%d\n", d1->v.eng);
}
【问题讨论】:
-
由于您没有为结构驱动程序分配内存,因此出现分段错误!您可以在堆栈上分配内存(通过声明驱动程序,
struct Driver d; struct Driver* pd=&d;)或通过调用malloc在堆上分配内存。struct Driver* pd = malloc(sizeof(struct Driver));
标签: c struct segmentation-fault gdb