user1544337
user1544337

Reputation:

Printf pointer in decimal notation

How can I print a pointer in decimal notation?

None of the below produce the desired result when compiling with -Wall. I understand the errors, and do want to compile with -Wall. But then how can I print a pointer in decimal notation?

#include <stdio.h>
#include <stdlib.h>

int main() {
    int* ptr = malloc(sizeof(int));
    printf("%p\n", ptr);                 // Hexadecimal notation
    printf("%u\n", ptr);                 // -Wformat: %u expects unsigned int, has int *
    printf("%u\n", (unsigned int) ptr);  // -Wpointer-to-int-cast
    return EXIT_SUCCESS;
}

(This is needed because I'm using the pointers as node identifiers in a dot graph, and 0x.. is not a valid identifier.)

Upvotes: 3

Views: 1613

Answers (2)

user8068585
user8068585

Reputation: 9

There is a report that 'some' platforms do not provide PRI*PTR macros in their inttypes.h files. If it's your case, try printf("%ju\n", (uintmax_t)ptr); instead.

... Though I think you should have those macros because you looks to be working with GNU C.

Upvotes: 1

Bjorn A.
Bjorn A.

Reputation: 1178

C has a datatype named uintptr_t, which is large enough to hold a pointer. One solution is to convert (cast) your pointer to (uintptr_t) and print it like shown below:

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

int main(void) 
{
    int* ptr = malloc(sizeof *ptr);
    printf("%p\n", (void *)ptr);                 // Hexadecimal notation
    printf("%" PRIuPTR "\n", (uintptr_t)ptr);
    return EXIT_SUCCESS;
}

Note that %p expects a void* pointer, gcc will warn if you compile your code with -pedantic.

string format for intptr_t and uintptr_t seems to be relevant too.

Upvotes: 8

Related Questions