C++ 将 void 指针增加一字节?两个?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6449935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:09:49  来源:igfitidea点击:

Increment void pointer by one byte? by two?

c++cpointers

提问by Adam S

I have a void pointer called ptr. I want to increment this value by a number of bytes. Is there a way to do this?

我有一个名为ptr. 我想将这个值增加一些字节。有没有办法做到这一点?

Please note that I want to do this in-place without creating any more variables.

请注意,我想在不创建更多变量的情况下就地执行此操作。

Could I do something like ptr = (void *)(++((char *) ptr));?

我可以做类似的事情ptr = (void *)(++((char *) ptr));吗?

回答by James McNellis

You cannot perform arithmetic on a void pointer because pointer arithmetic is defined in terms of the size of the pointed-to object.

您不能对 void 指针执行算术运算,因为指针算术是根据指向对象的大小定义的。

You can, however, cast the pointer to a char*, do arithmetic on that pointer, and then convert it back to a void*:

但是,您可以将指针转换为 a char*,对该指针进行算术运算,然后将其转换回 a void*

void* p = /* get a pointer somehow */;

// In C++:
p = static_cast<char*>(p) + 1;

// In C:
p = (char*)p + 1;

回答by Alok Save

No arithmeatic operations can be done on voidpointer.

不能对void指针进行算术运算。

The compiler doesn't know the size of the item(s) the voidpointer is pointing to. You can cast the pointer to (char *) to do so.

编译器不知道void指针指向的项目的大小。您可以将指针转换为 ( char *) 来执行此操作。

In gcc there is an extension which treats the size of a voidas 1. so one can use arithematic on a void*to add an offset in bytes, but using it would yield non-portable code.

在 gcc 中有一个扩展将 a 的大小void视为1. 因此可以在 avoid*上使用算术以字节为单位添加偏移量,但使用它会产生不可移植的代码。

回答by tdammers

Just incrementing the void*does happen to work in gcc:

只是增加void*确实在 gcc 中起作用:

#include <stdlib.h>
#include <stdio.h>

int main() {
    int i[] = { 23, 42 };
    void* a = &i;
    void* b = a + 4;
    printf("%i\n", *((int*)b));
    return 0;
}

It's conceptually (and officially) wrong though, so you want to make it explicit: cast it to char*and then back.

虽然它在概念上(和官方)是错误的,所以你想明确表示:将它投射到char*然后返回。

void* a = get_me_a_pointer();
void* b = (void*)((char*)a + some_number);

This makes it obvious that you're increasing by a number of bytes.

这使您很明显增加了许多字节。

回答by EyalSh

You can do:

你可以做:

++(*((char **)(&ptr)));