The difference between the two pieces of code is the difference between increasing the address that the pointer contains and changing the actual value.
The first piece of code: p += 1;
increases the address that p
is pointing to by one. For instance if x
is at address 124, then p
was first equal to 124 and is now increased to 125 (in a simple scenario, realistically this would increase by more as p
is an integer pointer and thus the increase would be more than 1 byte).
The second piece of code: *p +=1;
first dereferences the address in p
and adds one to the value currently stored in that address. For instance if x
is at address 124 and is of the value 42, then p
equals 124, but *p
is the deferenced pointer and is equal to 42
. You can then assign a new value to *p
to make the value at address 124 (i.e. the value of x
) equal to 43
.
EDIT: As mentioned by @Bathsheba, pointers are passed by value to function calls. This means that if we were to do the following, the original pointer y
would remain unchanged, whereas the address p
is pointing to does change as mentioned above.
void inc(int *p) {
p += 1;
}
int main() {
int x = 5;
int *y = &x;
inc(y);
return 0;
}
As for your second question on structs. Structs pointers still contain the address of the struct in memory, but the 'arrow notation' you refer to will implicitly do the dereferencing of the fields for you.