无效指针解释 [英] void pointer explanation

查看:166
本文介绍了无效指针解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我无法完全理解这段关于void指针的内容。

类型为void的指针,它可以获取从任何其他指针分配的地址(除了函数指针)并且可以重新分配给其他指针类型。无效指针无法解除引用。他们充当占位符。

有人可以用一个例子来解释吗?

谢谢

Hi,
I can't understand exactly this paragraph about void pointers.
Pointer of type void which can take address assigned from any other pointer (except function pointer) and can be reassigned to other pointer type. Void pointers cannot be dereferenced. They act as place holder.
can anyone explain it with an example?
thanks

推荐答案

这很简单一次你可以绕过它:

无效指针可以保存任何类型数据的地址:

It's pretty simple once you get you head round it:
A void pointer can hold the address of any kind of data:
void* vp;
int* ip = &ai[2];
char* cp = "hello";
vp = ip;
vp = cp;

所有都有效。



但是因为你不能将变量声明为

All are valid.

But since you can't declare a variable as

void v;



你不能dereferrence指针通过尝试访问它指向的值:


You can't "dereferrence" the pointer by trying to access the value it is pointing at:

*vp = i;
DoSomething(vp->member);

两者都是非法的。



除此之外还有充分的理由可理解的缺乏void类型变量:指针并不完全相同。指向int的指针只能保存在字边界上对齐的物理地址 - 因为整数是基于字的值。 Char Ballard指针不是,因为字符是字节对齐的。

Both are illegal.

There are good reasons for this, apart from the understandable lack of a "void" type variable: pointers are not all the same. A pointer to an int can only hold physical addresses which are aligned on a word boundary - because integers are word based values. Char Ballard pointers aren't, because chars are byte aligned.


作为你的段落答案和评论都说, void * 只是指向任何类型的内存块的指针。 Void * 可以指向任何类型的内存,但 void * 无法取消引用。



但这并不完全正确。当然你不能取消引用 void * 但是你可以,如果你输入它所指向的类型。



As your "paragraph" the answer and the comments all say, void* is just a pointer to a memory block of any type. Void* can point to memory of any type but void* cannot be dereferenced.

But this is not totally true. Of course you cannot dereference a void*. But you can, if you type-caste it to the type which it points to.

int a;
void *p = &a;

int new_a;
new_a= *p; //this line is wrong
new_a= *(int*)p; //but this works





这是一个巧妙的技巧,通常有助于在C / C ++中实现通用数据类型。



This is a neat trick and it often helps to implement generic data types in C/C++.


这篇关于无效指针解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆