Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do i get 2 different output from when printing out the sizeof() pointer vs variable

Why do i get 2 different output from when printing out the value in the same address?

the pointer ptr is pointing at the index 0 of the accessed Element (bar).

yet is showing me different results?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

unsigned int bar[5];


int main(){

unsigned int * ptr = &bar[0];

printf("%lu\n",sizeof(ptr)); // Console output : 8 (bytes)
printf("%lu\n",sizeof(bar[0])); //Console output : 4 (bytes)
  return 0;
}

>Solution :

Why do i get 2 different output from when printing out the value in
the same address?

These two statements

printf("%lu\n",sizeof(ptr)); // Console output : 8 (bytes)
printf("%lu\n",sizeof(bar[0])); //Console output : 4 (bytes)

do not output "values in the same address".

The first statement outputs the size of the pointer ptr that has the type unsigned int *. This statement is equivalent to

printf("%zu\n",sizeof( unsigned int * )); // Console output : 8 (bytes)

The second call of printf outputs the size of an object of the type unsigned int. This call is equivalent to

printf("%zu\n",sizeof( unsigned int ) ); //Console output : 4 (bytes)

As you can see the arguments of the expressions with the operator sizeof in these two calls of printf are different

printf("%zu\n",sizeof( unsigned int * )); // Console output : 8 (bytes)
printf("%zu\n",sizeof( unsigned int ) ); //Console output : 4 (bytes)

If you will rewrite the second call of printf for example the following way

printf("%xu\n",sizeof( bar + 0 ) ); //Console output : 8 (bytes)

then you will get the same value as the value produced by the firs call because the expression bar + 0 has the type unsigned int * due to the implicit conversion of the array designator to a pointer to its first element in this expression.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading