Here is my sample code
#include<stdio.h>
void main()
{
int arr[]={1,2,3,4,5,6};
char *ptr,a;
a='c';
ptr=&a;
int *ptr1,a1;
a1=4;
ptr1=&a1;
printf("%d %d %d",sizeof(arr), sizeof(ptr1), sizeof(ptr));
}
Now, as far as I understand, size of will tell me the size required to store the variable, now the output for this one is
24 4 4
Why is the size of arr=24, after all it’s just a pointer and it should be having size =4 ?
Thanks.
“…after all it’s just a pointer…”? No. Array is not a pointer. Array is an array object: a solid continuous block of memory that stores the array elements, no pointers of any kind involved. In your case array has 6 elements of size 4 each. That is why your
sizeofevaluates to 24.The common misconception about arrays being pointers has been debunked millions of times, but somehow it continues to pop up now and then. Read the FAQ, come back if you have any questions about it
http://c-faq.com/aryptr/index.html
P.S. As @Joachim Pileborg correctly noted in his answer,
sizeofis not a function. It is an operator.Another context in which arrays behave differently from pointers is the unary
&operator (the “address of” operator). When unary&is applied to a pointer of typeint *is produces a pointer of typeint **. When unary&is applied to an array of typeint [10]is produces a pointer of typeint (*)[10]. These are two very different types.It is another popular source of questions (and errors): sometimes people expect
&to produce aint **pointer when applied to anint [10]array.