Reputation: 833
I'm trying to declare an array of pointers of a struct
some_struct
in C
Can I do:
some_struct* arr[10];
instead of:
some_struct** arr=(some_struct**)malloc(10*sizeof(some_struct*));
And what's the difference?
Upvotes: 1
Views: 83
Reputation: 471209
In the first case, the lifetime of the array is only the scope at which it is defined in. When it falls out of scope, it will be freed automatically so you don't have to do any clean up.
In the second case, the array lives beyond the scope where the pointer is declared. So you will need to manually free()
it later to avoid a memory leak.
Upvotes: 5
Reputation: 75130
The first is allocated on the stack.
The second is allocated on the heap.
free
(it is said to have dynamic storage duration)free
on it before you lose all pointers to it (in this case, before the pointer to it goes out of scope), you will have a memory leakrealloc
on the pointer to the array to ask the C runtime to try to make it bigger (or smaller) in place (or move it to a different larger area of memory if resizing it in place is not possible)Upvotes: 1
Reputation: 2127
some_struct* arr[10];
Will allocate the memory on the stack, while some_struct** arr=(some_struct*)malloc(10*sizeof(some_struct*));
will allocate it on the heap.
Upvotes: 0
Reputation: 4367
The first one will be allocated in the stack, the second in the heap
Upvotes: 0