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 ?
Yes, it is, and
sizeof(val)produces the size for the "pointer to the array", not the array itself.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 gives8.Also, as I mentioned, use
%zuto printsize_t, the type produced bysizeofoperator.