0

Possible Duplicate:
void * arithmetic

Hi guys I have a small question regarding pointer increment in C. First let say that I know that ptr++, where ptris a pointer will increment as much as the sizeof(*ptr). Also I know that when doing *ptr, the compiler knows it has to grab sizeof(*ptr) bytes from memory.

The second part helps me understand why the following does not even compile:

int main(){
 int a = 3;
 void* b = &a;
 printf("%d\n", *b);
 return 0;
}

Because the compiler does not know the size of a variable of type void. However, I'm a little bit confused about the following code:

int main(){
 int a = 3;
 void* b = &a;
 printf("%p\n", b);
 b++;
 printf("%p\n", b);
}

So, my two questions are:

  1. How is the compiler able to know how much it should increment b?

  2. Why does it increment only one byte (at least in my machine is one byte)?

Community
  • 1
  • 1
Fred
  • 16,367
  • 6
  • 50
  • 65

1 Answers1

7

1) it doesn't, 2) that's undefined behaviour. void is an incomplete type, so it doesn't have a well-defined size, so you cannot do pointer arithmetic with its pointers.

Typically you will want char pointers for byte-wise memory fiddling.

If you compile with all compiler warnings enabled, you will spot such problematic code.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • 1
    Well, you don't necessarily need _all_ the warnings, but you should definitely try a few of them on for size. – Chris Lutz Nov 06 '11 at 20:37
  • 1
    @ChrisLutz: In GCC, I'd recommend `-W -Wall -Wextra -pedantic` (hence "all"), which gives you a *very* good basis. The compiler offers some more esoteric and subjective warnings (like `-Weffc++` for C++ for checking conformity to Scott Meyers's C++ book!) which I'm happy to skip ;-) Basically any warning that lets you know about blatant misuse of the language should be enabled... – Kerrek SB Nov 06 '11 at 21:21
  • gcc provides arithmetic on void pointers as an extension though. It treats the size as 1 when doing arithmetic. http://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/Pointer-Arith.html – nos Nov 06 '11 at 21:27
  • @KerrekSB - I use `-Wall -Wextra -Werror` and a few others as well, but one of those (I think it's `-Wall`) turns on a warning for `if(x = something)`, which I don't like (I think the double parenthesized version it recommends to silence the warning is ugly). I wish you could disable warnings as easily as you could enable them. – Chris Lutz Nov 06 '11 at 23:20
  • @ChrisLutz: Really? I get: `warning: suggest parentheses around assignment used as truth value [-Wparentheses]` This is on GCC 4.6.2. – Kerrek SB Nov 06 '11 at 23:44
  • @KerrekSB - That's the warning I don't like. I just find the extra parentheses to be a bit too Lispy. – Chris Lutz Nov 07 '11 at 00:44
  • @ChrisLutz: Ah, I understand. In your case you want `-Wno-parentheses` then :-) – Kerrek SB Nov 07 '11 at 00:47