0

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));
2
  • 1
    If I am not mistaken, this code never asks for the size of a pointer... It just contains a confusion about what an empty array and dynamic memory are. Commented May 11, 2021 at 14:36
  • In all cases, in p=tab; p=malloc(5*sizeof(int)); the second statement will overwrite whatever p was pointing to. This can't modify tab. Commented May 11, 2021 at 14:45

1 Answer 1

6

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.