Paminu wrote:
If I have this struct:
typedef struct test{
int x;
int y;
}container;
Now I would like to make an array of 5 pointers to this struct:
int main(void){
container *cp[5];
cp=malloc(sizeof(container));
container->content="big";
container->tt=malloc(sizeof(container *)*5); //THIS LINE GIVES ERROR!
return 0;
}
But how do I allocate space for these pointers? Do I have to do it for each
one at a time?
You wrote container *cp[5]. That means you already allocated space
for 5 pointers to container objects. cp[0]..cp[4] are all pointers
pointing who knows where... Now, if you want to allocate space
for a container object and make cp[3] point to it, you could do:
cp[3]=malloc(sizeof(container));
and
cp[3]->x=something;
cp[3]->y=something_else;
use free(cp[3]) to free the allocated space that cp[3] points to.
If you have a global variable:
container gcp;
you can say cp[3]=&gcp;
You should not free the pointer as you haven't allocated space,
the program did. Also, pay attention if you do that with auto
(local) variables as they are destroyed when the function, they
are defined in, ends.
--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)