I have a pointer array of items that I read in from a file. These items are typedef structs
.
My array is resizable as the file contains a lot of items.
while (fscanf(fp, "%X %[^\n]", &code, string) != EOF) {
if (list->length >= list->capacity) {
list->capacity *= 2;
list->items = (Item**)realloc(list->items,
list->capacity * sizeof(Item*));
}
item.code = code;
strcpy(item.string, string);
list->items[list->length++] = &item;
}
Assume list
and item
are declared already. Space is malloced for list.
static List * list;
&
Item item = { 0, { 0 } };
are declared and initialized earlier in the code. list
is a global variable by necessity.
If I try to iterate this completed list by attempting to get the first value for instance:
printf("line %d: %X\t%-89s\n", 1, list->items[0]->code, list->items[0]->string);
I will get the last element in the file from this. However if I were to include this printf
in the aforementioned while loop, I will get desired console output (when the index is list->length
).
Why would I be experiencing this type of behavior? Is there something I am forgetting about traversing pointers?