简体   繁体   中英

why do we need to use (void*)&a instead of &a

int main()
{
  int a;
  int* b;
  a = 40;
  b = &a;
  printf("the address of a is %p, and the value of a is %d \n",&a, a);
  return 0;
}

I find that both (void*)&a and &a print the same thing. So why do people still add (void*) ? Is it just a habit?

You use specifier %p to print address stored in pointer, and this format specifier expects type to be void * . And as &a is of type int * , cast void * is used .

The printf() format specifier %p expects a void* type pointer. Since what you are passing might not be a void* type pointer, and the standard does not mandate for all pointers to have the same format, is is important that you cast a pointer to void* before passing it to printf.

For instance:

int* a = malloc(sizeof(int));
printf("a is %p",(void*)a);

Is done as best practice incase int* and void* are not similar

Firstly, different pointer types are not necessarily interchangable.

Secondly, for varargs no implicit conversion takes place as the compiler does not know the expected type.

C Standard says that using an incorrect specifier for an argument in printf will result in undefined behavior.

7.21.6.1 The fprintf function

  1. If a conversion specification is invalid, the behavior is undefined. 282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

Since pointer to int is not the same type as pointer to void , and %p may only be used for a pointer to void and even if some other rules says that any pointer may be converted to pointer to void and back, that doesn't change the fact that the behavior is undefined, because of the quoted rule.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM