uwhpsc-2016 / lectures

Notes, slides, and code from the in-class lectures.
7 stars 21 forks source link

Statically Allocated Arrays #4

Open alyfarahat opened 8 years ago

alyfarahat commented 8 years ago

Let's say we have a statically allocated array as in foo()

void foo()
{
   int arr[] = {1, 2, 3, 4};
   printf("%p \n", arr);
   printf("%p \n", &arr);
}

Since arr is known at compile time, there is no need to allocate a pointer type for it to hold its value. The compiler shall substitute the constant value of arr everywhere a reference to arr is made in the code. The above code prints the same value for arr and &arr.

I think the situation is different when the array is dynamically allocated since, int this case, arr is a mutable pointer type.

void bar()
{
   int n = 10;
   int * arr = malloc( n * sizeof(int) );

   printf("%p \n", arr);
   printf("%p \n", &arr);
   free(arr);   
}

which prints two different values, one for arr and the other for &arr. In fact *arr is stored on the heap while the pointer arr itself is on the stack.

I am slightly confused as to why arr and &arr take the same value when arr is statically allocated.

mvelegar commented 8 years ago

@alyfarahat The reason why arr and &arr take the same value when arr is statically allocated is because the compiler does not actually assign any memory to &arr (zero memory variable) on the stack, but assigns a relative “reference” to the 1st element of the array (it just knows where the first element of arr is). It prints out the address of the first element of the arr both times when arr is statically allocated. Try this instead:

void main(char* args[]) {
    int arr[] = {1, 2, 3, 4};
    int *arr2 = arr;
    printf("%p\n", arr2);
    printf("%p\n", &arr2);
}

Now you will get two different numbers. Now &arr2 is actually assigned memory on the stack, so you will get two different numbers.