Reputation: 1520
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);
}
Upvotes: 0
Views: 201
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