Search code examples
arrayscpointersreferencememory-address

Does arrays in C takes separate memory to store the address of the first element?


In many tutorial videos and explanations of C programming, for representing arrays like int a[5] = {9,2,1,3,4}; Tutors/teachers always make a separate box for storing the address of first element of array i.e address of 9 in this case.

Which means that the total memory consumed by the array should be (memory consumed by the constant pointer a to store the address of first element + 5*(sizeof(int)).

If that's the case then why this program which is mentioned below gives such an output.

Program

#include <stdio.h>
int main() 
{ 
    int a[5] = {6,1,2,9,3}; 
    int * p = a;
    printf("a is %u\n", a); 
    printf("&a is %u\n", &a);
    printf("&a+1 is %u\n", &a+1);
    printf("p is %u\n", p); 
    printf("&p is %u", &p); 
    return 0; 
} 

Output

a is 2128206832
&a is 2128206832
&a+1 is 2128206852
p is 2128206832
&p is 2128206824

Here a and &a give the same address. Which shouldn't be the case at all when looking at the representation mostly used by the people to represent arrays in C. According to their diagram representation of array, it should have given different values for a and &a, just like p and &p. So how array is truly represented inside of the memory? Sorry for such a trivial doubt, but I am confused.

  • And does a create a separate memory space to store the address of first element of array?
  • If yes then why a and &a is giving same value?
  • It should have differed just like p and &p.

Solution

  • No, a does not create a separate memory to store the address of array. &a gives address of array and a gives address of a[0]. Both &a and a are same a because the address of the first element is same as address of the array. int a[5] does precisely what it looks like , generates array of 5 elements. When you create p , you create a separate variable which has a value that &a[0]. You may look into this for more clarity. You should also look at this