0
votes

I found that we can print the pointer value with %p format specifier. N1570 7.21.6.1(p8):

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

Since the pointer to void can be converted to pointer to any other object type I'm curious would the conversion by hand is necessary. Example:

struct test_t{
    int a;
}

void foo(){
    struct test_t *test_ptr = malloc(sizeof(*test_ptr));
    printf("Pointer test_ptr = %p\n", test_ptr);
}

Here I did not convert it to void * assuming that the compiler does this for me. Is it conforming? Or I should convert such pointers to void * on my own like

printf("Pointer test_ptr = %p\n", (void *) test_ptr);

The Standard specifies that the representation of and alignment of void * is the same as char *. It is not specified if the void * representation/alignement is must be the same as any object type.

1
Short answer - yes, you need the cast to void-pointer4386427

1 Answers

2
votes

The version with (void *) is correct, and your original code causes undefined behaviour. (You already provided the relevant Standard quote so I have no need to add further quotes).

Since the pointer to void can be converted to pointer to any other object type I'm curious would the conversion by hand is necessary

"can be" means there is potential for a conversion to happen. Such a conversion only actually happens when it was requested , with the language standard specifying which constructs request a conversion.

For the arguments to printf, only the default argument promotions are applied. There are not any other conversions.