(void *)在类型转换的上下文中意味着什么?

时间:2017-11-09 15:16:15

标签: c pointers void void-pointers

以下代码中的(void *)是什么意思?我尝试删除(void *)类型转换但它仍然可以正常工作并打印usrInt变量的地址。你能解释一下吗?

#include <stdio.h>

int main(void) {
   int usrInt = 0;    // User defined int value
   int* myPtr = NULL; // Pointer to the user defined int value

   // Prompt user for input
   printf("Enter any number: ");
   scanf("%d", &usrInt);

   // Output int value and location
   printf("We wrote your number into variable usrInt.\n");
   printf("The content of usrInt is: %d.\n", usrInt);
   printf("usrInt's memory address is: %p.\n", (void*) &usrInt);
   printf("\nWe can store that address into pointer variable myPtr.\n");

   // Grab location storing user value
   myPtr = &usrInt;

   // Output pointer value and value pointed by pointer
   printf("The content of myPtr is: %p.\n", (void*) myPtr);
   printf("The content of what myPtr points to is: %d.\n", *myPtr);

   return 0;
}

2 个答案:

答案 0 :(得分:1)

通常,转换为void *或来自printf()只是多余的,因为对于任何数据指针类型,此转换都隐含在C中。

将指针传递给可变参数函数是一种需要强制转换的特殊情况。

printf()可变参数函数。 int printf(const char *format, ...); 原型看起来像这样:

format

这意味着编译器看不到void *之后的参数的任何类型声明。因此,它不知道传递的类型应该是int *,因此转换不会自动发生。

通常,省略强制转换不会产生任何可见效果,因为在大多数实现中,所有指针都具有完全相同的内部表示。 但是C标准不保证,因此可以在例如将void *转换为%p时,While True:会有不同的表示形式。如果省略强制转换,那么您的代码在技术上是不正确的(它会调用未定义的行为以便为转换传递错误的类型if),并且会在指向表示指针的平台上导致错误的结果不同的类型是不同的。

答案 1 :(得分:0)

c11:7.21.6格式化输入/输出功能(p8):

  

return back(); - 参数应为指向void的指针。指针的值以实现定义的方式转换为打印字符序列。

相关问题