Search code examples
arrayscprintfsizeofpointer-to-array

Memory allocation for pointer to an array in c?


#include <stdio.h>
int main()
{
 int (*ptr) [5];
 printf ("%lu\n" , sizeof (ptr));
 printf ("%lu\n" , sizeof (*ptr));
}

I am using 64 bit system. When I run this code in gcc compiler it generate output 8 and 20 . My question is how many byte going to allocate for this pointer to an array ? It is 8 or 20 and why?


Solution

  • ptr designates an object that will store the address of a 5-element array of int. On your system, such a pointer takes up 8 bytes of storage.

    The expression *ptr can designate an object that is a 5-element array of int; on your system, such an array takes up 20 bytes (5 4-byte elements).

    Assume the code:

    int (*ptr)[5] = malloc( sizeof *ptr );
    

    This gives you something like the following (each box takes up 4 bytes):

         +---+        +---+
    ptr: |   | -----> |   | (*ptr)[0]  // we don't want to index into ptr,
         + - +        +---+            // we want to index into what ptr
         |   |        |   | (*ptr)[1]  // *points to*, hence the explicit
         +---+        +---+            // dereference on ptr.  
                      |   | (*ptr)[2]  //
                      +---+            // Since a[i] is defined as *(a + i),
                      |   | (*ptr)[3]  // (*ptr)[i] == (*(ptr + 0))[i] ==
                      +---+            // (ptr[0])[i] == ptr[0][i]
                      |   | (*ptr)[4]  //
                      +---+
    
    sizeof  ptr == sizeof (int (*)[5]) ==  8 // assuming 8-byte addresses
    sizeof *ptr == sizeof (int [5])    == 20 // assuming 4-byte int
    

    This is equivalent to writing

    int arr[5];            // sizeof arr == sizeof (int [5])    == 20
    int (*ptr)[5] = &arr;  // sizeof ptr == sizeof (int (*)[5]) ==  8
    

    The size of a pointer does not depend on the size of the thing it points to.