Error Performing Pointer Arithmetic on void * in MSVC

一曲冷凌霜 提交于 2019-12-21 05:18:29

问题


Error    1    error C2036: 'const void *' : unknown size    file.cpp     111

I don't follow. GCC never complains about void * pointer arithmetic, even on -ansi -pedantic -Wall. What's the problem?

Here's the code-

struct MyStruct {

    const void *buf;    // Pointer to buffer  
    const void *bufpos; // Pointer to current position in buffer

};

...

size_t    someSize_t, anotherSize_t;
MyStruct *myStruct = (MyStruct *) userdata;
...
  if ( (myStruct->bufpos + someSize_t) > 
       (myStruct->buf + anotherSize_t) ) { // Error on this line
     ...

回答1:


You can't do pointer math on a void * pointer. Cast oData->bufpos and oData->anotherConstVoidPtr to something the compiler knows how to deal with. Since you seem to be looking for sizes, which are presumably in bytes, casting to char * should work:

if (((char *)oData->bufpos + someSize_t) ...



回答2:


On the line:

if ( oData->bufpos ...

The type of bufpos is still void*. The compiler doesn't know what that pointer points to, so it gives you that error.

For pointer arithmetic, void* has no size, so taking an offset, or doing other pointer arithmetic doesn't make sense. Cast it to char* if you want to offset it by a number of bytes:

if(((char*)oData->bufpos) + offset ...

Edited after more code/context was given

If you can help it, try to use char* instead of void*. People in C-land will know what you are talking about, because chars are bytes, and you'll save yourself the headache of casting.




回答3:


$3.9.1/9- The void type has an empty set of values. The void type is an incomplete type that cannot be completed. It is used as the return type for functions that do not return a value. Any expression can be explicitly converted to type cv void (5.4). An expression of type void shall be used only as an expression statement (6.2), as an operand of a comma expression (5.18), as a second or third operand of ?: (5.16), as the operand of typeid, or as the expression in a return statement (6.6.3) for a function with the return type void.

I suspect an improper use of 'void' beyond what is allowed by the Standard.



来源:https://stackoverflow.com/questions/3498850/error-performing-pointer-arithmetic-on-void-in-msvc

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