【发布时间】:2018-04-22 15:43:40
【问题描述】:
以下代码中的 (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;
}
【问题讨论】:
-
%p使用指向void的指针。当不强制转换时,行为在技术上是未定义的。 -
没有要求
void*在内存中的大小与int*相同——现在很清楚为什么需要这样做以避免未定义的行为?
标签: c pointers void void-pointers