Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Performing Pointer Arithmetic on void * in MSVC

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
     ...
like image 652
A Student at a University Avatar asked Dec 06 '22 01:12

A Student at a University


2 Answers

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) ...
like image 186
Carl Norum Avatar answered Dec 07 '22 16:12

Carl Norum


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.

like image 28
Merlyn Morgan-Graham Avatar answered Dec 07 '22 15:12

Merlyn Morgan-Graham