struct element {
int val;
int z;
};
typedef struct element ELEM;
Look at this example:
int main()
{
ELEM z;
z =
Declaring a pointer doesn't create anything but a pointer. Gotta have something for it to point to, which is what malloc
gives you.
Alternatively, you could have created the struct on the stack (a.k.a. "automatic storage"):
ELEM z;
ELEM *p = &z;
(*p).val = 3; // Also could be written as p->val = 3;
printf("%d",(*p).val);
BTW, your pointer code has an error, in that it leaks (i.e. loses track of) the first allocated struct:
ELEM *p;
p = (ELEM*)malloc(sizeof(ELEM));
(*p).val = 3;
p = (ELEM*)malloc(sizeof(ELEM)); // <- leak here: pointer to old struct lost.
printf("%d",(*p).val);
Deleting the second malloc
fixes the problem. A full, fixed-up version that looks more like code you'd see in use:
ELEM *p = (ELEM*)malloc(sizeof(ELEM));
p->val = 3;
printf("%d\n", p->val);
free(p);
Every malloc
should have a free
, unless your program releases it memory by terminating. And even then, it's nice to have the free
.