下面代码中的(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;
}
最佳答案
通常,与 void *
之间的转换只是多余的,因为对于任何数据指针类型,此转换在 C 中都是隐式的。
将指针传递给可变参数函数是一种需要强制转换的特殊情况。
printf()
是一个可变参数函数。 printf()
原型(prototype)如下所示:
int printf(const char *format, ...);
这意味着编译器看不到 format
之后的参数的任何类型声明。因此,它不知道传递的类型应该是 void *
,因此转换不会自动发生。
通常,省略强制转换不会产生任何明显的效果,因为在大多数实现中,所有指针都具有完全相同的内部表示形式。 但是 C 标准并不能保证这一点,因此可以在以下情况下实现: int *
在转换为 void *
时将具有不同的表示形式。如果您省略强制转换,您的代码在技术上是不正确的(它会调用未定义的行为来传递错误的类型进行转换%p
),并且会在以下平台上导致错误的结果:不同类型的指针的表示是不同的。
关于c - (void*) 在类型转换中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47205375/