tadm123 tadm123 - 3 months ago 8
C Question

Initializing a member of a structure with pointers (C)

I'm a begginer and have been reading books on C, I have a question about pointers of structures.
Below I tried to initialize members of the structure using a "*p" pointer

#include <stdio.h>

struct part{
int num;
char *name;
};

int main()
{
struct part *p; //creating a pointer with 'struct part' type

p->num= 5; //initializing
p->name= "Jose";

printf("%d\n",p->num);
printf("%s",p->name);

return 0;
}


Probably a dumb question but I'm interest to know why is it wrong? The program is crashing obviously.

Answer

You declared a pointer but it doesnt point to anything.

You'd have to do e.g. p = malloc(sizeof(struct part)) or maybe struct part q; p = &q; or otherwise set it to point to something first.

Check out the C version of this old classic.