Hi, I have a typedef'd struct with a pointer member:
1 2 3 4
typedefstruct
{
int *i;
} TEMP;
I want to set the VALUE of this member:
1 2
TEMP temp;
*(temp.i) = 42;
I would think that temp.i would be a pointer, then I would dereference it with *, then set the value. The code compiles but the program crashes at that point. Can someone explain what I'm doing wrong?
Another Q. If I wanted to use malloc, would I have to malloc each member in the struct, or can I just malloc the pointer to the struct? The latter seems to crash on me:
It would be a pain if I had to malloc a struct with a lot of pointers, so can somebody tell me if I'm doing something wrong or if there's an easier way?
Thanks, I have just two more questions. If the structure contained non-pointer members, do I have to malloc them in the same way I would malloc a pointer? Also, in your code R0mai, I noticed in line 8:
t->i = malloc(sizeof(t->i));
It would return a pointer to a memory block of 4 bytes, since that's the size of a pointer right? Isn't it supposed to be:
t->i = malloc(sizeof(*t->i));
so that it returns a memory block of how big t->i is, and not how big a pointer is?