22

I'm trying to do some basic pointer arithmetic with a void *. My actual code computes an offset by using sizeof and then multiplying. Here is sample code to show an instance of the issue by itself.

void * p;
p = 0;
p = p + 1;

I'm using the MSVC compiler in C (not C++).

The error is:

expression must be a pointer to a complete object type  

I'm not understanding what this error is trying to say. There is no object or struct here.

101010
  • 14,866
  • 30
  • 95
  • 172
  • Not really. I read it first. – 101010 Jun 29 '14 at 02:49
  • 5
    `void` has no size, hence pointer arithmetic on a `void *` isn't allowed. – user3386109 Jun 29 '14 at 02:49
  • This sounds like it might be it. It says that adding to a void * is a GCC extension. (weird because it works in the C++ mode of the MSVC compiler) http://stackoverflow.com/questions/20154575/error-void-unknown-size – 101010 Jun 29 '14 at 02:49
  • I am having a hard time finding a dup but there must be one, see [Declaring type of pointers?](http://stackoverflow.com/a/20407956/1708801) for now. – Shafik Yaghmour Jun 29 '14 at 02:51
  • http://stackoverflow.com/questions/3523145/pointer-arithmetic-for-void-pointer-in-c – mafso Jun 29 '14 at 02:54

1 Answers1

35

Pointer arithmetic is always in terms of the size of the pointed-to object(s). Incrementing a char* will advance the address by one, whereas for int* it would usually be four (bytes). But void has unknown size, so pointer arithmetic on void* is not allowed by the standard. Cast to the appropriate type first; if you just want to manipulate the address as if it were a number then cast to char* or use intptr_t.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436