I am trying to understand pointers and char arrays in C programming. I have a struct called player defined as such:
typedef struct player{
char* name;
float ppm;
} player;
And I have the following in Main:
int main()
{
player* head = (player*) malloc(sizeof(player));
char* meName = &(head->name);
(*head).name = "potato";
(*head).name = "Paul";
(*head).ppg =7.6;
//printf("player is named %s\n", *meName); //First print
printf("player is named %s\n", meName); //second print
printf("player is named %s\n", (*head).name); //third print
return 0;
}
Why does my first print cause a segmentation fault, and why do my other two prints output the following:
player is named k0@
player is named Paul
If I am not mistaken meName
should be pointing to a memory address that is then changed by using another pointer to that same memory address. In fact, if I print it as in my 2nd print, it shows that address. Why is dereferencing it cause for a segFault
when I clearly set the variable to point to a memory space that was altered right after? Why would it not change to Paul
? And why would it throw a segfault in the first place?
Also, I'd appreciate an explanation of the arrow -> vs the * used to dereference pointers.