Open alyfarahat opened 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.
Let's say we have a statically allocated array as in
foo()
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 ofarr
everywhere a reference toarr
is made in the code. The above code prints the same value forarr
and&arr
.I think the situation is different when the array is dynamically allocated since, int this case,
arr
is a mutable pointer type.which prints two different values, one for
arr
and the other for&arr
. In fact*arr
is stored on the heap while the pointerarr
itself is on the stack.I am slightly confused as to why
arr
and&arr
take the same value whenarr
is statically allocated.