(void*) 在类型转换的上下文中是什么意思?
What does (void*) mean in context of typecasting?
下面代码中的(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;
}
c11: 7.21.6 格式化 input/output 函数 (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.
通常,转换为 void *
或从 void *
进行转换只是多余的,因为对于任何数据指针类型,此转换在 C 中都是隐式的。
将指针传递给 可变参数 函数是一种需要强制转换的特殊情况。
printf()
是一个 可变参数 函数。 printf()
原型如下所示:
int printf(const char *format, ...);
这意味着编译器看不到 format
之后的参数的任何类型声明。因此,它不知道传递的类型应该是 void *
,因此转换不会自动发生。
通常,省略转换不会产生任何可见的效果,因为在大多数实现中,所有指针都具有完全相同的内部表示。 但是 C 标准并不能保证,所以实现是可能的,例如int *
在转换为 void *
时会有不同的表示。如果你省略了转换,你的代码在技术上是不正确的(它调用 未定义的行为 来传递错误的转换类型 %p
)并且会在表示的平台上导致错误的结果指向不同类型的指针是不同的。
下面代码中的(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;
}
c11: 7.21.6 格式化 input/output 函数 (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.
通常,转换为 void *
或从 void *
进行转换只是多余的,因为对于任何数据指针类型,此转换在 C 中都是隐式的。
将指针传递给 可变参数 函数是一种需要强制转换的特殊情况。
printf()
是一个 可变参数 函数。 printf()
原型如下所示:
int printf(const char *format, ...);
这意味着编译器看不到 format
之后的参数的任何类型声明。因此,它不知道传递的类型应该是 void *
,因此转换不会自动发生。
通常,省略转换不会产生任何可见的效果,因为在大多数实现中,所有指针都具有完全相同的内部表示。 但是 C 标准并不能保证,所以实现是可能的,例如int *
在转换为 void *
时会有不同的表示。如果你省略了转换,你的代码在技术上是不正确的(它调用 未定义的行为 来传递错误的转换类型 %p
)并且会在表示的平台上导致错误的结果指向不同类型的指针是不同的。