The output of following program
#include<stdio.h>
int main(){
int *p[10];
printf("%ld %ld\n",sizeof(*p),sizeof(p));
}
is
8 <--- sizeof(*p) gives size of single element in the array of int *p[10]
80 <--- sizeof(p) gives size of whole array which is 10 * 8 in size.
now see the following program
#include<stdio.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
printf("sizeof(array) = %ld \n",sizeof(array));
printf("sizeof(array[0]) = %ld \n",sizeof(array[0]));
printf("sizeof int %ld\n",sizeof(int));
printf("TOTAL_ELEMENTS=%ld \n",TOTAL_ELEMENTS);
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
is
sizeof(array) = 28
sizeof(array[0]) = 4 <--here
sizeof int 4
TOTAL_ELEMENTS=7
What I am not able to understand is why is the sizeof(array[0]) different in both the outputs.
Best Answer
int *p[10];
is an array of pointers.*p
is the first element of that array of pointers. So it is a pointer to an integer. It is not an integer.int array[] = {23,34,12,17,204,99,16};
is an array of integers. Soarray[0]
is the first element of that array. So it is an integer.The size of a pointer to an integer (
*p
) and an integer (array[0]
) are different.So
sizeof(*p)
andsizeof(array[0])
are different.sizeof(p)
gives the size of the array of pointers. So it is: 10 x 8 = 80.i.e. (number of elements) x (size of one element)
sizeof(array)
gives the size of the array of integers. So it is: 7 x 4 = 28.