I am using the following piece of code as a learning exercise for pointers:
int a=8;
int *ptr=&a;
printf("\nThe & address of a is: %x\n",&a);
printf("\nThe value of the pointer ptr is: %p \n",ptr);
I am doing this to identify the address values given by &a and ptr and I am noticing the following difference in the output:
The & address of a is: a6bff9c4
The value of the pointer ptr is: 000000f5a6bff9c4
I can see that the ptr value is the & value with 000000f5 appended in the beginning. I know that %x outputs the & address value in hexadecimal. What is the format of the pointer value and how is it different from the hexadecimal & value?
Trying to understand the difference between the memory addresses outputted by & and pointer variable and understanding their formats.
The conversion specification
%xexpects an object of the typeunsigned int.sizeof( unsigned int )usually is equal to4. Whilesizeof( int * )is equal to4or8bytes depending on the used system.Using invalid conversion specification results in undefined behavior.
From the C Standard (7.21.6.1 The fprintf function)
Instead of this call where with a pointer there is used the conversion specification
%xyou should write
you need to write
And in the second call of
printfyou need to convert the pointer to the typevoid *.Here is a demonstration program.
The program output might look like
This call of
printfcan be more flexible if to rewrite it the following way