-5

Other than being able to dereference a void**, I don't understand the following:

void * foo, **bar;
foo++;//error
bar++;//no error

Why doesn't the first work but the second does? What's the difference?

Yu Hao
  • 115,525
  • 42
  • 225
  • 281
shinzou
  • 5,460
  • 9
  • 55
  • 115

1 Answers1

8

First snippet

 foo++;//error

because, foo is pointer to void and you cannot have pointer arithmetic on void *, size of the void type is not defined.

Second snippet,

 bar++;//no error

because, bar is a pointer to a pointer to void. So, arithmetic operation is permitted, as the size of a pointer to pointer type is well defined.

FWIW, don't get surprised if sometimes, void pointer arithmetic "works" without any error.

Sourav Ghosh
  • 130,437
  • 16
  • 177
  • 247
  • It worth mentioning that pointer arithmetic resulting in addresses within an unallocated space is UB. So `bar++` is not safe as well. – Eugene Sh. Jul 08 '15 at 19:10
  • @EugeneSh.Yes my question is specifically for allocated spaces, I tried to make my question as minimal as possible. – shinzou Jul 08 '15 at 19:12
  • Can you please answer the other part of my question? – shinzou Jul 08 '15 at 19:37
  • I also added another small question just now. – shinzou Jul 08 '15 at 19:39
  • @EugeneSh., no arithmetic that goes one item beyond a valid object is allowed, so `bar++` is fine. It is only erroneous when you'd increment further away from a valid object or dereference the pointer. – Jens Gustedt Jul 08 '15 at 20:02