Jordan Davis
Jordan Davis

Reputation: 1520

Printing the value of a structure pointer variable member

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

enter image description here

//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);
}

Upvotes: 0

Views: 201

Answers (1)

ouah
ouah

Reputation: 145829

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

Either use 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 ->).

Upvotes: 2

Related Questions