C++ 警告:算术中使用了“void *”类型的指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26755638/
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 11:41:40  来源:igfitidea点击:

warning: pointer of type ‘void *’ used in arithmetic

c++pointersvoid-pointerspointer-arithmetic

提问by user1876942

I am writing and reading registers from a memory map, like this:

我正在从内存映射中写入和读取寄存器,如下所示:

//READ
return *((volatile uint32_t *) ( map + offset ));

//WRITE
*((volatile uint32_t *) ( map + offset )) = value;

However the compiler gives me warnings like this:

但是编译器给了我这样的警告:

warning: pointer of type ‘void *' used in arithmetic [-Wpointer-arith]

How can I change my code to remove the warnings? I am using C++ and Linux.

如何更改我的代码以删除警告?我正在使用 C++ 和 Linux。

回答by Sean

Since void*is a pointer to an unknown type you can't do pointer arithmetic on it, as the compiler wouldn't know how big the thing pointed to is.

由于void*是一个指向未知类型的指针,您不能对其进行指针运算,因为编译器不知道所指向的东西有多大。

Your best bet is to cast mapto a type that is a byte wide and then do the arithmetic. You can use uint8_tfor this:

最好的办法是转换map为一个字节宽的类型,然后进行算术运算。您可以uint8_t为此使用:

//READ
return *((volatile uint32_t *) ( ((uint8_t*)map) + offset ));

//WRITE
*((volatile uint32_t *) ( ((uint8_t*)map)+ offset )) = value;

回答by Vlad from Moscow

Type void is incomplete type. Its size is unknown. So the pointer arithmetic with pointers to void has no sense. You have to cast the pointer to type void to a pointer of some other type for example to pointer to char. Also take into account that you may not assign an object declared with qualifier volatile.

void 类型是不完整的类型。它的大小是未知的。所以用指向 void 的指针的指针算法是没有意义的。您必须将指向 void 类型的指针转​​换为其他类型的指针,例如指向 char 的指针。还要考虑到您可能不会分配使用限定符 volatile 声明的对象。

回答by Damien

If the use of arithmetic on void pointers is really what you want as it is made possible by GCC (see Arithmetic on void- and Function-Pointers) you can use -Wno-pointer-arithto suppress the warning.

如果在空指针上使用算术确实是您想要的,因为 GCC 使之成为可能(请参阅空指针和函数指针上的算术),您可以使用它-Wno-pointer-arith来抑制警告。