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

你说的曾经没有我的故事 提交于 2020-01-02 00:53:15

问题


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.


回答1:


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.

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

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

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



回答2:


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.




回答3:


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-arith to suppress the warning.



来源:https://stackoverflow.com/questions/26755638/warning-pointer-of-type-void-used-in-arithmetic

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