简体   繁体   English

将void指针强制转换为char指针指针是否安全

[英]Is it safe to cast void pointer to char pointer pointer

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. 这对我的几个盒子没有问题,但是想知道它是否会在某些系统上引起问题。

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 * . 你使用void **的唯一情况是当你计划取消引用它以获得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 ** . 正如您在http://codepad.org/UcZUA0UL上看到的,无论您使用void*还是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. 在您实际使用指针之前,无论如何都要将它转换回char ** - 所以它永远不会被取消引用,而它是void

The casting (and usage afterwards) from void* , if the original pointer was char ** . 如果原始指针是char ** ,则从void*转换(以及之后的用法)。

You shouldn't use void** . 你不应该使用void**

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

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