2

Are the following two methods of creating arrays in C equivalent?

int main( void )
{
    int *array = malloc(sizeof(int) * 10);
    int array2[10];
}

My thought is that method two is syntactic sugar for method one, but I'm not sure.

Also, what do array and array2 contain after these declarations? I know array is a pointer to the start of an array, but what is the array initialized to? How about for array2?

2
  • No they are not the same. Do some reading on stack vs heap memory and what malloc actually does. Commented Jan 28, 2016 at 0:28
  • One declares an array. The other declares a pointer, calls malloc and makes the pointer to hold the value that malloc returned. Commented Jan 28, 2016 at 2:19

1 Answer 1

5

They are not remotely equivalent. This:

int *array = malloc(sizeof(int) * 10);

will allocate a block of memory of the heap, and leave you with a pointer to that memory.

This:

int array2[10];

will allocate some memory on the stack. Read this excellent answer about stack and heap memory: What and where are the stack and heap?

Sign up to request clarification or add additional context in comments.

8 Comments

So array will persist until the program exits whereas array2 will go out of scope as soon as the function it is created in returns. For both, we have no way of knowing what the values are intially (i.e. they're not all initialized to 0 or something).
Or you could say that array is allocated at runtime (dynamically) whereas array2 is allocated statically at compile time. Assuming array2 is declared in the main() function.
@user3386109 Fair enough. Say this was all happening in main() then. Then the two methods would be essentially equivalent (except we might run into problems if we tried to create a really large array on the stack).
@user3386109 If I did int array[10] inside some function I call in main then array would go out of scope as soon as the function returns.
@Adam You seem to be saying that they are "basically equivalent, except for <list of all the ways in which they're not equivalent>". Along those lines, statues and oranges are basically equivalent, except that statues are art pieces and oranges are fruit, statues are bigger than oranges, oranges are edible while statues aren't, oranges are a commodity while statues are often unique, and so on.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.