Originally Posted by
nkhambal
You need to use array of pointers or pointer-to-pointer to your struct, if you want to create multiple pointers to a give struct
Well that's debatable, and incidently, I've been meaning to for some time now. I see it often stated that the above is the case, but it's really not true.
You don't use pointers-to-pointers when you want multiple characters. And, in fact, you can resize that. So why should it be any different with structures?
Code:
struct foo *ptr;
ptr = malloc( sizeof *ptr );
The above will allocate one structure instance and point to it.
Code:
char *ptr = malloc ( 10 * sizeof *ptr );
This will allocate 10 characters. Now usually everyone leaves off the "sizeof *ptr" part when allocating characters, because the size of a character is always 1. However, I'm including it as an illustration of how the two allocations are identical.
Code:
struct foo *ptr = malloc( 10 * sizeof *ptr );
Will allocate 10 structure instances, and point to them. (All of these assume malloc doesn't fail.)
You can walk through a list of pointers with a pointer to that type, simply by doing:
Code:
walk = ptr;
walk++;
This holds true for characters as well as any other data type where you're allocating in said fashion.
There are only two reasons you need pointers to pointers: First, you're trying to update what a pointer you pass to a function points at. That is, pass the address of a pointer to a function so you can make it point to something new. Second, to pretend you've got a multiple dimension array.
There is no need for either of this in this example. A simple realloc will suffice here.
Code:
struct foo *tmp = realloc( ptr, newsize * sizeof *ptr );
[edit]
Curses, foiled again. That's it, no more proof reading for me!
[/edit]
Quzah.