flint_stone
flint_stone

Reputation: 833

basic about pointer array

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

Answers (4)

Mysticial
Mysticial

Reputation: 471209

  • The first one puts the array on the stack.
  • The second one allocates it on the heap.

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

Seth Carnegie
Seth Carnegie

Reputation: 75130

The first is allocated on the stack.

  • Its lifetime is the surrounding scope, and you don't have to manually deallocate the memory it occupies since it will be deallocated when the enclosing scope ends (it is said to have an automatic storage duration)
  • Compile-time arrays like this must have a constant size (that is, the size must be known at compile time, not runtime. Unless you are using C99 which allows Variable Length Arrays (VLAs) or the GCC compiler which has a non-standard extension to allow that
  • Once they are created, they cannot be resized

The second is allocated on the heap.

  • Its lifetime is until you manually deallocate it with free (it is said to have dynamic storage duration)
  • If you don't use 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 leak
  • The size of these arrays can be determined at runtime
  • You can use realloc 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

Michael Robinson
Michael Robinson

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

Eregrith
Eregrith

Reputation: 4367

The first one will be allocated in the stack, the second in the heap

Upvotes: 0

Related Questions