Is it safe to cast void pointer to char pointer pointer

久未见 提交于 2019-12-24 02:23:26

问题


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

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

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.


回答1:


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 *.

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.




回答2:


The casting (and usage afterwards) from void*, if the original pointer was char **.

You shouldn't use void**.



来源:https://stackoverflow.com/questions/10555320/is-it-safe-to-cast-void-pointer-to-char-pointer-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!