Reputation: 165
In the following code I initialize an int pointer and after I dynamically allocated the memory.
But when I want to display the size of the array it does not show me the value 5:
int *p=NULL;
int tab[]={};
p=tab;
p=malloc(5*sizeof(int));
printf("sizeof(tab)=%d",(int)sizeof(tab));
Upvotes: 0
Views: 60
Reputation: 222724
int *p=NULL;
defines p
to be a pointer and initializes it to be a null pointer.
int tab[]={};
is not defined by the C standard, because the standard requires arrays to be non-empty. However, some compilers will allow this and create an array of zero length. (There is essentially no use for such an array other than as the last member of a structure or perhaps a member of a union.)
p=tab;
sets p
to point to where the first element of tab
would be, if the array were not empty.
p=malloc(5*sizeof(int));
reserves memory for 5 int
and sets p
to point to that memory.
printf("sizeof(tab)=%d",(int)sizeof(tab));
prints the size of tab
. Since tab
is a zero-length array, it prints “sizeof(tab)=0” in implementations that support this.
Further, had you printed sizeof p
, it would print the size of the pointer p
, not the size of what it points to. sizeof
reports information about the type of its operand. Type is compile-time information. sizeof
does not report execution-time information such as how much memory was reserved at a certain location. (Except it will report sizes for variable-length arrays.)
Upvotes: 6