将void指针强制转换为char指针指针是否安全? [英] Is it safe to cast void pointer to char pointer pointer

查看:354
本文介绍了将void指针强制转换为char指针指针是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道这样铸造是否安全:

Just wondering if it's safe to cast like this:

char **cpp;
// ... allocation and what not 
void *vp = (void *)cpp;
// ...
cpp = (char **)vp;

应该使用void **还是void *可以吗?这可以在我的几个盒子上正常工作,但想知道它是否会在某些系统上引起问题.

should a void ** be used or is void * fine? This works on a couple of my boxes without issue but was wondering if it could cause problems on certain systems.

推荐答案

强制转换始终是安全的,只要指针有效,则取消引用是安全的. 唯一打算使用void **的情况是,当您打算取消引用以获得void *时.

The cast is always safe, dereferencing it is safe as long as the pointer is valid. The only case where you'd use a void ** is when you plan to dereference it to get a void *.

但是,除非您执行指针算术运算,否则它实际上并不重要.正如您在 http://codepad.org/UcZUA0UL 上看到的那样,无论是否使用void*void **.在实际使用指针之前,无论如何都要将其转换回char **-因此在void -ish时永远不会取消引用它.

However, unless you do pointer arithmetics it won't really matter. As you can see on http://codepad.org/UcZUA0UL it works fine no matter if you use void* or void **. Before you actually use the pointer you are going to cast it back to char ** anyway - so it is never dereferenced while it's void-ish.

这篇关于将void指针强制转换为char指针指针是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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