I know that the unary operator ++ adds one to a number. However, I find that if I do it on an int pointer, it increments by 4 (the sizeof an int on my system). Why does it do this? For example, the following code:
int main(void)
{
int *a = malloc(5 * sizeof(int));
a[0] = 42;
a[1] = 42;
a[2] = 42;
a[3] = 42;
a[4] = 42;
printf("%p\n", a);
printf("%p\n", ++a);
printf("%p\n", ++a);
return 0;
}
will return three numbers with a difference of 4 between each.
It’s just the way C is – the full explanation is in the spec, Section 6.5.6 Additive operators, paragraph 8:
To relate that to your use of the prefix
++operator, you need to also read Section 6.5.3.1 Prefix increment and decrement operators, paragraph 2:And also Section 6.5.16.2 Compound assignment, paragraph 3: