-2

If I do this:

int x = 10;
void *ptr = &x;
ptr++;

The line "ptr++" gives an error.

However, If instead of "ptr++" I do this:

ptr = ptr + 1;

It works just fine. What could be the reason?

mb1994
  • 241
  • 3
  • 13

2 Answers2

4

Void pointer arithmetic is illegal in standard C but usually allowed by gcc extensions.

Conceptually, this is because when you perform an increment on a pointer, it will actually perform scaling in the background to add the proper number of bytes (given by the pointer's type) to get you to the next unit of data.

Since a void pointer could point to any type, it's saving you from accessing parts of memory differently than intended. The compiler can't possibly determine how to scale the addition since it has no knowledge of the type pointed to.

In standard C, ptr = ptr + 1 is also illegal for the same reason. The reason you're seeing one work is due to the same issues with gcc extensions.

Both will give you errors in gcc when using the -pedantic-errors flag.

Purag
  • 16,941
  • 4
  • 54
  • 75
  • So you mean to say that both should give errors according to C standards? And that the second one works because of different compilers? – mb1994 Jul 19 '15 at 18:04
  • Yeah, lots of machines have lots of different extensions for gcc that might allow some things but not others. But, you can use the `-pedantic-errors` flag to report errors according to the C standard. – Purag Jul 19 '15 at 18:09
  • In an ideal world, either both or none of these would work, since they're the same thing in native code anyway. But alas... – Purag Jul 19 '15 at 18:13
1

C standard forbids pointer arithmetics on void*. Depends on compiler though. The reason is simple, C is not assembly :-)

Hitokage
  • 733
  • 8
  • 19