An array of structures
How is an array of structures created in C without knowing the eventual amount of structures to be stored in the array?
I would like to loop in a for loop, create a开发者_如何转开发 tempStruct set its variables, add this to an array and then loop again, creating a new tempStruct and adding it to the array.
Im having some issues wrapping my head around how this is done in C while trying to relate from objective C.
Dynamically allocated arrays (using malloc
) can be reallocated (using realloc
).
Therefore the solution will look something like this:
malloc
initial array (arbitrary size)- while still space in array, add structures
- when array full,
realloc
to bigger size - goto 2
You could create a double linked list which points to parent and child
struct list{
list* next;
list* prev;
special_data* data;
}
easy to do and flexible
You can't create an array in C without knowing number of it's members up front. Your options for adding are:
- (Faster) Create new array with +1 element, copy entire array and add new element to the end
- (Better) Create your own implementation of linked list (Linked list) which will dynamically allocate memory for each new member.
You can use malloc to create your structure.
Edit: The following demonstrates one way to do what you're asking by creating a linked list:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int data;
void* next;
} tempStruct;
#define NUM_STRUCTS 4
int main(void) {
tempStruct* cur_ptr;
tempStruct* root_ptr;
int i;
root_ptr = malloc(sizeof(tempStruct));
root_ptr -> data = 0;
root_ptr -> next = NULL;
cur_ptr = root_ptr;
for (i = 1; i < NUM_STRUCTS; i ++ ) {
tempStruct* new_ptr = malloc(sizeof(tempStruct));
new_ptr -> data = i;
new_ptr -> next = NULL;
cur_ptr -> next = new_ptr;
cur_ptr = cur_ptr -> next;
}
cur_ptr = root_ptr;
while (cur_ptr != NULL) {
printf("cur_ptr -> data = %d\n", cur_ptr -> data);
cur_ptr = cur_ptr -> next;
}
return 0;
}
If you really want to create something that acts more like an array, you'll need to allocate all your memory at the same time, using something like:
the_data = malloc(NUM_STRUCTS * sizeof(tempStruct);
Then you'll have to access the data with the dot operator (i.e. '.' (no quotes in your code).
struct foo {int bar;};
size_t i = 0, n = 8;
struct foo *arr = malloc(n * sizeof *arr);
int bar;
while ((bar = get_next_bar()) != -1) {
if (++i == n) { // no room for new element; expand array
arr = realloc(arr, n *= 2);
if (arr == NULL) abort; // see note below.
}
arr[i] = (struct foo){bar};
}
The number of assigned elements in the array is i+1
. Don’t forget to free()
the array when you’re done with it.
Note: In real programs you generally do not do p = realloc(p, s)
directly. Instead you assign the result of realloc()
to a new pointer, then do error detection & handling before clobbering your original pointer.
精彩评论