简体   繁体   English

为什么我们需要使用(void *)&a而不是&a

[英]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. 我发现两者(void*)&a&a打印相同的东西。 So why do people still add (void*) ? 那么为什么人们仍然添加(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 * . 使用说明符%p打印存储在指针中的地址,此格式说明符要求类型为void * And as &a is of type int * , cast void * is used . 并且因为&aint *类型,所以使用了cast void *

The printf() format specifier %p expects a void* type pointer. printf()格式说明符%p需要void*类型指针。 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. 由于您传递的内容可能不是void*类型指针,并且标准并未要求所有指针具有相同的格式,因此在将指针传递给printf之前将其转换为void*非常重要。

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 作为最佳实践,incase int*void*不相似

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. 其次,对于varargs,由于编译器不知道期望的类型,因此不会发生隐式转换。

C Standard says that using an incorrect specifier for an argument in printf will result in undefined behavior. C Standard表示在printf中使用不正确的说明符将导致未定义的行为。

7.21.6.1 The fprintf function 7.21.6.1 fprintf函数

  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. 282)如果任何参数不是相应转换规范的正确类型,则行为未定义。

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. 因为指向int的指针与 指向void的指针的类型不同,并且%p只能用于指向void指针 ,即使其他一些规则指出任何指针都可以转换为指向void和back的指针 ,那么由于引用的规则,更改了行为未定义的事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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