C 为什么我在尝试使用指针访问结构时会出现这种分段错误?

C 为什么我在尝试使用指针访问结构时会出现这种分段错误?,c,struct,segmentation-fault,gdb,C,Struct,Segmentation Fault,Gdb,我正在努力学习嵌套结构。当我使用结构变量访问它时,它工作正常。 但当我尝试使用指针访问它时,它会显示分段错误 #include <stdio.h> #include <stdlib.h> struct Vehicle { int eng; int weight; }; struct Driver { int id; float rating; struct Vehicle v; }; void main() { str

我正在努力学习嵌套结构。当我使用结构变量访问它时,它工作正常。 但当我尝试使用指针访问它时,它会显示分段错误

#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);
}
#包括
#包括
结构车辆{
国际工程;
整数权重;
};
结构驱动程序{
int-id;
浮动评级;
结构车辆v;
};
void main(){
结构驱动程序*d1;
d1->id=123456;
d1->评级=4.9;
d1->v.eng=456789;
printf(“%d\n”,d1->id);
printf(“%f\n”,d1->rating);
printf(“%d\n”,d1->v.eng);
}

在取消引用之前,必须初始化指向有效缓冲区地址的指针

例如:

void main(){
    struct Driver d; /* add this */
    struct Driver *d1;
    d1 = &d; /* add this */

另外,我建议您在托管环境中使用标准的
int main(void)
,而不是
void main()
,这在C89和C99或更高版本中定义的实现中是非法的,除非您有特殊原因使用非标准签名。

您使用了指针
d1
,但没有初始化它

您需要首先初始化它,例如使用
malloc

struct Driver *d1 = malloc(sizeof(struct Driver));

if(NULL == d1)
{
    perror("can't allocate memory");
    exit(1);
}

// ... using d1

free(d1);
return 0;

您需要先初始化指针,然后才能访问它所指向的内容。这里有一种解决方法:

    struct Driver data;
    struct Driver *d1 = &data;
    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);
注意添加了
数据
,并初始化了指向它的
d1
。运行时,它会生成:

123456
4.900000
456789

初始化它的另一种方法是通过
malloc
使用动态分配的内存,在这种情况下,您稍后会释放分配的内存。

由于没有为结构驱动程序分配内存,因此出现了分段错误!您可以在堆栈上分配内存(通过声明驱动程序,
struct Driver d;struct Driver*pd=&d;
),也可以通过调用
malloc
在堆上分配内存<代码>结构驱动程序*pd=malloc(sizeof(结构驱动程序))您应该检查
malloc()
返回值并调用
free()
。请将此添加到您的答案中。