空指针算术 [英] Void Pointer Arithmetic
问题描述
给定一个void指针,如果我想使void指针指向x字节在前面,这将是最好的做法?
Given a void pointer, if I want to make the void pointer point to x bytes ahead, how will this be best done? Is there a better way than casting to a char pointer?
推荐答案
有更好的方法吗?转换成
a字符指针?
Is there a better way than casting to a char pointer?
否(除非有 char *
而不是 void *
开头,所以你不必强制转换)。
No (except having a char *
instead of a void *
to begin with, so you don't have to cast it at all).
如果这是不可取或不可能的,那么唯一的方法是:
If this is not desirable or possible, then the only way is:
ptr = static_cast<char *>(ptr) + offset;
(注意:如果你用C ++做这类东西,通常有一个更好的解决方案。除非你是一个专家,你已经排除了所有其他的选择,我建议你发布一个新的问题,如果有一个更好的方法来做你想做什么!)
(Note: if you are doing this sort of stuff in C++, usually there is a much better solution. Unless you are an expert and you already ruled out every other alternative, I suggest you post a new question asking if there is a better way to do what you're trying to do!)
这篇关于空指针算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!