-1
void inc(int *p) {
    p += 1;
}

int main() {
    int x = 5;
    inc(&x);

    printf("x = %d\n", x);

    return 0;
}

I've figured that this code doesn't increase the value of x.
It works when I change

void inc(int *p) {
    p += 1;
}

to

void inc(int *p) {
    *p += 1;
}

Kind of got confused with pointers right now.
Can someone help me?
Thank you in advance!

Haxify
  • 419
  • 4
  • 9
  • 17
  • 1
    `p` -> Address of x, `*P` -> value where the Address is pointing to – Rizier123 Dec 12 '14 at 08:05
  • Interesting that you think the pointer being a parameter of a function has anything to do with it. – juanchopanza Dec 12 '14 at 08:06
  • @Rizier123 Is this different from getting a pointer of a structure as a parameter? I've noticed that when I take pointer of a structure as a parameter, I can simply use arrow to mutate its value without putting star in front of it. – Haxify Dec 12 '14 at 08:07
  • Start reading a C primer. http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list – harper Dec 12 '14 at 08:10
  • @harper I'll do that, thank you! – Haxify Dec 12 '14 at 08:13

1 Answers1

1

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.

MrHug
  • 1,315
  • 10
  • 27
  • What about when function takes pointer of a structure as a parameter? No need for asterisk when mutating the value in the given structure; what's the difference? – Haxify Dec 12 '14 at 08:12
  • @Haxify: The asterisk is needed if you use the `.` operator. It is not, if you use the `something->foo` operator, which is a shortcut for `(*something).foo` – urzeit Dec 12 '14 at 08:26