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?
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;
}
CodePudding user response:
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("%zu\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.
CodePudding user response:
ptr is a unsigned int *. The size of this kind of pointer is 8 bytes in that environment.
bar[0] is a unsigned int. The size of this is 4 bytes in that environment.
Maybe you thought you were using *ptr?
