简体   繁体   English

c中的空指针

[英]Void pointers in c

I just wrote this lines of code expecting them to work just fine but I keep getting an error which says "invalid use of void expression" and i have no clue why我只是写了这行代码,希望它们能正常工作,但我一直收到一个错误,提示“无效使用 void 表达式”,我不知道为什么

int main(){
   int a=12;
   void* ptr = &a;
   printf("%d",*ptr);
}

I thought void pointers can point to any type of data so what's the issue here.我认为 void 指针可以指向任何类型的数据,所以这里有什么问题。 I even tried to cast the void pointer to an integer pointer but I still get the same error.我什至尝试将 void 指针转换为整数指针,但我仍然遇到相同的错误。

You can not dereference a void pointer, the underlying type ( void ) is incomplete.您不能取消引用 void 指针,基础类型 ( void ) 是不完整的。 You should either use a different type for your pointer (such as int* ) or you should cast your void pointer to a complete type (again, probably int* ).您应该为您的指针使用不同的类型(例如int* ),或者您应该将您的 void 指针转换为一个完整的类型(同样,可能是int* )。

You can't dereference a void* , as you've seen, but casting it to an int* most definitely works:正如您所见,您不能取消引用void* ,但将其转换为int*绝对有效:

printf("%d",*(int*)ptr);

OnlineGDB demo在线GDB演示

I thought void pointers can point to any type of data so what's the issue here.我认为 void 指针可以指向任何类型的数据,所以这里有什么问题。

A void * can point to any type of data 1 . void *可以指向任何类型的数据1 But it only remembers the address, not the type.但它只记住地址,不记得类型。 To use it with * , you must tell the compiler what type to use:要将它与*一起使用,您必须告诉编译器要使用什么类型:

int a = 12;
void *ptr = &a;
printf("%d\n", * (int *) ptr);  // Use cast to specify type.

During execution, the program will not remember that ptr was assigned an address from an int and automatically know to load an int in the printf call.在执行过程中,程序不会记住ptr是从int分配的地址,并自动知道在printf调用中加载int During compilation, the compiler will not remember this either.在编译过程中,编译器也不会记住这个。 To use the pointer to access data, you must convert it back to an appropriate type, then use that.要使用指针访问数据,您必须将其转换回适当的类型,然后使用它。

Footnote脚注

1 A pointer should retain all the qualifiers of any object it is set to point to. 1指针应保留其指向的任何对象的所有限定符。 A pointer to a const int x or volatile int x ought to be assigned to a const void *p or a volatile void *p , respectively, not a void *p without the qualifiers.指向const int xvolatile int x的指针应该分别分配给const void *pvolatile void *p ,而不是没有限定符的void *p

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

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