Confused about pointer adding/subtracting

I am very confused.                                                              Output:
1
2
3
4
5
int a[2];
a[0] = 3;
a[1] = 7;
int *p = a;
cout << *p + *(p+sizeof(int)) << endl;
10
I compiled and ran this on two separate computers. My assumption is that adding X to pointers makes it point to a value X bytes later. (I have never had to deal with adding to/subtracting from pointers that point to types larger than one byte, so I could be completely off on this assumption) However, I get a strange error with this:
6
7
8
void *vp = new int[2];
vp + 4; //error C2036: 'void *' : unknown size
delete[] vp;
Surely it should understand that a void pointer can be incremented by X bytes?
Last edited on
closed account (o1vk4iN6)
It's just as the error says, void doesn't have a size.

1
2
3
4
5
int a[5];

cout << a[4] << endl;
//equivalent
cout << *(a + 4) << endl;


essentially when you add "4", you are actually adding "4 * sizeof(int)" to the pointer. Since void isn't a type it doesn't know what size to increment by.

If you want to increment by bytes than typecast to "char*".

EDIT: just so it doesn't confuse you, int a[5] is techniquelly a pointer, just it allocates local memory (stack) and places the pointer to that memory in it for you.
Last edited on
Oh, huh - I guess I got really lucky on both computers >_<

Thanks!
Topic archived. No new replies allowed.