Search code examples
carrayspointerssizeofpointer-to-array

How is pointer to array different from array names?


I was reading more about arrays vs pointers in C and wrote the following program.

#include <stdio.h> 

int arr[10] = { } ; 
typedef int (*type)[10]  ;
int main()
{
   type val = &arr ; 
   printf("Size is %lu\n", sizeof(val)) ; 
   printf("Size of int is %lu\n", sizeof(int)) ;
}

If, I execute this program, then sizeof(val) is given to be 8 and sizeof(int) is given to be 4.

If val is a pointer to the array with 10 elements, shouldn't it's size be 40. Why is the sizeof(val) 8 ?


Solution

  • If val is a pointer to the array...

    Yes, it is, and sizeof(val) produces the size for the "pointer to the array", not the array itself.

    ...shouldn't it's size be 40.?

    No, sizeof(val) calculates the size of the operand, the "pointer" here. In your platform, the size of a pointer seems to be 64 bits, i.e., 8 bytes. So, it gives 8.

    Also, as I mentioned, use %zu to print size_t, the type produced by sizeof operator.