Reputation: 31109
I have an array of pointers to structs.
struct key {
int *data;
};
struct key *entry = NULL;
entry = malloc(sizeof(entry));
Reallocated a bit of times:
node = realloc(node, (length+1)*sizeof(node[0]));
node[length].data = some_int;
In another part of my program, I want to iterate through it. I don't know how much elements it is containing at the moment.
for (i=0; &(node[i]) != NULL; i++)
length = i;
But I have infinity loop. Because:
(gdb) p node[i]
$1 = {data = 0x0}
It seems to like an uninitialized value, but it is not NULL
pointer.
How to determine the end of an array?
Why it is not NULL
pointer?
Upvotes: 1
Views: 640
Reputation: 30489
&(node[i])
is same as node + i
and as long as node is not null and i is not zero, this will be non-null.
If you want to mark end of array, I would suggest always (re)allocate one extra element and initialize pointer member of termination with NULL.
struct key *temp = realloc(node, (length+2)*sizeof(node[0]));
if(NULL == temp) { /* Updated as per suggestion from @alk */
/* Handle error and return */
}
node = temp;
node[length].data = address_of(some_int);
node[length+1].data = NULL;
And later while looping
for (i=0; node[i].data != NULL; i++)
length = i;
But an even better solution would be to keep length
you last used to realloc bundled with node
. This way you won't need to calculate it using a loop.
Upvotes: 1
Reputation: 70901
&(node[i])
takes the address of node[i]
.
So
&(node[i]) != NULL
will always be true, as the address of node[i]
will always be different from NULL
.
Upvotes: 2