打印结构指针变量成员的值

时间:2023-01-13 22:57:19

Why am I getting a "segmentation fault" error when I run this after compiling?

编译后运行此错误时,为什么会出现“分段错误”错误?

打印结构指针变量成员的值

//CODE

//码

#include <stdio.h>
#include <string.h>

void main(){

    struct name{
        char first[20];
        char last[20];
    } *person;

    strcpy(person->first, "jordan");
    strcpy(person->last, "davis");

    printf("firstname: %s\n", person->first);
    printf("lastname: %s\n", person->last);
}

1 个解决方案

#1


2  

Because person pointer has not been initialized. So there is no valid struct name object when you dereference the pointer.

因为人指针尚未初始化。因此,当您取消引用指针时,没有有效的结构名称对象。

Either use malloc:

要么使用malloc:

person = malloc(sizeof *person);

or just declare an object of type struct name instead of struct name * (and then don't forget to access your structure members with . operator instead of ->).

或者只是声明一个struct name类型的对象而不是struct name *(然后不要忘记使用。运算符而不是 - >访问你的结构成员)。

#1


2  

Because person pointer has not been initialized. So there is no valid struct name object when you dereference the pointer.

因为人指针尚未初始化。因此,当您取消引用指针时,没有有效的结构名称对象。

Either use malloc:

要么使用malloc:

person = malloc(sizeof *person);

or just declare an object of type struct name instead of struct name * (and then don't forget to access your structure members with . operator instead of ->).

或者只是声明一个struct name类型的对象而不是struct name *(然后不要忘记使用。运算符而不是 - >访问你的结构成员)。