Case I:
int a[12];
printf("%d",sizeof(a));
Case II:
int *a = (int *)malloc(12*sizeof(int));
printf("%d",sizeof(a));
The above two code snippets return different outputs,
48
in the first case4
in the second case
Why is it so?
Case I:
int a[12];
printf("%d",sizeof(a));
Case II:
int *a = (int *)malloc(12*sizeof(int));
printf("%d",sizeof(a));
The above two code snippets return different outputs,
48
in the first case 4
in the second caseWhy is it so?
Because arrays are not pointers and vice-versa. Period.
To elaborate, in case of int a[12];
, a
is an array, which has got it's own properties. It is of type array, so when you pass the array name to sizeof
operator, it gives you the size of the array (in your case, 12 int
s, multiplied by size of an int
, 4, total 48).
OTOH, int *a = malloc(12*sizeof*a);
(corrected format), a
is a pointer, and using sizeof
on this will give you only the size of the pointer itself, not the size of the memory allocated (pointed by) to the pointer.
To quote the C-faq, chapter 6,
Q: But I heard that
char a[]
was identical tochar *a
?A: Not at all. (What you heard has to do with formal parameters to functions). Arrays are not pointers, though they are closely related.
The array declaration
char a[6]
requests that space for six characters be set aside, to be known by the namea
. That is, there is a location nameda
at which six characters can sit. The pointer declarationchar *p
, on the other hand, requests a place which holds a pointer, to be known by the namep
. This pointer can point almost anywhere: to anychar
, or to any contiguous array ofchars
, or nowhere.
Notes:
malloc()
and family in C
..Arrays and pointers are different datatypes in C. When array is used as an operand with sizeof
operator , it gives the size of array data type. But, when a pointer is used with sizeof
operator, size of pointer is returned.
Standard says (C11-6.5.3.4):
The
sizeof
operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand.
The type of operand a
in first case is int [12]
while the type of operand in second case is int *
.
You are getting different answers because in the two cases a
is different.
int a[12];
— in this a
is an array,
int *a = malloc(12*sizeof*a);
— in this a
is a pointer.
Pointers and arrays can be used interchangeably at most of the places, but that does not mean they are the same things. Both have different properties (as explained by Sourav).
sizeof
operator deals with the size of type. It does not have to do anything with the contents held by the operands passed to it.
int a[12]
as a type int [12]
and therefore give size 48(4*12)
.
But int *a
is an integer pointer and sizeof
operator give size of the pointer (i.e 4
).
Both in these cases int a[12]
and int *a
are not same.
Note that sizeof
is one of the few cases where an array does not decay to a pointer.