Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Programming-Stack and Heap Array Declarations

Tags:

c++

c

Suppose I declare an array as int myarray[5]

Or declare it as int*myarray=malloc(5*sizeof(int))


Will both the declarations set equal amount of memory in number of bytes? Without considering that the former declaration is for the stack and the latter on the heap.

Thank you!

like image 604
Code_Jamer Avatar asked Dec 11 '22 21:12

Code_Jamer


1 Answers

There's a fundamental difference, that may not be apparent in the way you use myarray:

  • int myarray[5]; declares an array of five integers, and the array is an automatic variable (and it is uninitialized).

  • int * myarray = malloc(5 * sizeof(int)); declares a variable that is a pointer to an int (also as an automatic variable), and that pointer is initialized with the result of a library call. That library call promises to make the resulting pointer point to a region of memory that's big enough to store five consecutive integers.

Because of pointer arithmetic, array-to-pointer decay and the convention that a[i] is the same as *(a + i), you can use both variables in the same way, namely as myarray[i]. This is of course by design.

If you're looking for a difference, then maybe the following helps: The array-of-five-ints is a single object, and it has a definite size. By contrast, the malloc library call doesn't create any objects. It just sets aside enough memory (and suitably aligned), but it could for example allocate a lot more memory.

(In C++ there's of course the additional distinction between memory and objects.)

like image 153
Kerrek SB Avatar answered Dec 14 '22 09:12

Kerrek SB