When trying to print a pointer, for example
#include <stdio.h>
main() {
int a = 3;
printf("The address : %p\n", &a);
printf("As an hex : %x\n", &a);
return 0;
}
I get a 000000ac4f5ffd58
and the nice 4f5ffd58
(the first two characters mismatch is from unknown origin). It's just for comfort and beauty, the %x
"works" to display it. Is there any way to have the correct (0x4f5ffd58
) way to print my pointer (its format) ?
I'm using CLion (I resetted the settings), and here is the CMakeLists.txt
associated with it :
cmake_minimum_required(VERSION 3.22)
project(untitled C)
set(CMAKE_C_STANDARD 99)
add_executable(untitled main.c)
CodePudding user response:
The "correct" way I was thinking of it the
0x4f5ffd58
.
What is the "correct" part of it? The length? If you're on a 64bit system, a 32bit value is by no means "correct".
If you're looking for the 0x
intro, you might want to try the "alternative" format (printf("The address : %#p\n", (void *)&a);
). What exactly the standard and the alternative format might be is implementation-defined, but usually the alternative form provides the 0x
intro.
CodePudding user response:
Seems the problem was in my expectation.
In every C tutorial, the pointers is printed with the format 0x4f5ffd58
, but of course, as I redid every calculation now, 8*4 only makes a 32-bit address, where my system is a 64-bit, thus the longer displayed address (which confused me because I was first printing with the 0x
prefix, but no more, maybe due to an IDE update).
CodePudding user response:
You are using the conversion specifier x
designed to output objects of the type unsigned int
. Using it with a pointer invokes undefined behavior. Instead you could write for example
#include <stdio.h>
#include <inttypes.h>
int main( void )
{
int a = 3;
printf( "The address : %p\n", ( void * )&a );
printf( "As an hex : %#" PRIxPTR "\n", ( uintptr_t )&a );
return 0;
}
The program output might look like
The address : 0x7ffe9bf5f9b8
As an hex : 0x7ffe9bf5f9b8
Also bear in mind that according to the C Standard (7.21.6.1 The fprintf function)
p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.
And pay attention to that according to the C Standard the function main without parameters shall be declared like
int main( void )