6
votes

I am working with a C project using visual studio. I tried to compile the following code:

void shuffle(void *arr, size_t n, size_t size)
{
        ....
        memcpy(arr+(i*size), swp,  size);
        ....  
}

I get the following error with Visual studio Compiler:

error C2036: 'void *' : unknown size

The code compile well with GCC. How to solve this error?

1
But you are sure that you are compiling with a C compiler? - terence hill
Yes, It is removed. - ProEns08
However you cannot index pointer of type void. You can try to cast it to char so that each increment is of one byte - terence hill
Because the compiler does not know what size a void* pointer is, although there could be GCC extension that permits it. To do pointer arithmetic, you have to know the size of the data it points to. Note that adding 1 to a pointer to a 32-bit int will add 4 to the pointer itself. Just like with array indexing, where you access the second element with arr[1] not with arr[4]. - Weather Vane
Thanks all for your interesting remarks. - ProEns08

1 Answers

14
votes

You can't perform pointer arithmetic on a void * because void doesn't have a defined size.

Cast the pointer to char * and it will work as expected.

memcpy((char *)arr+(i*size), swp,  size);