as in the title, what's the difference because these two seem to get me the same results?
No they are not the same. Assume that d
is a pointer to int
:
int n = 0;
int* d = &n;
*d++; // d++ then *d, but d++ is applied after the statement.
(*d)++; // == n++, just add one to the place where d points to.
I think there is an example in K&R where we need to copy a c-string to another:
char* first = "hello world!";
char* second = malloc(strlen(first)+1);
....
while(*second++ = *first++)
{
// nothing goes here :)
}
The code is simple, put the character pointed by first
into the character pointed by second
, then increment both pointers after the expression. Of course when the last character is copied which is '\0', the expression results to false
and it stops!
The increment ++
has higher operator precedence than the dereference *
, so *d++
increments the pointer d
to point to the next location within the array, but the result of ++
is the original pointer d
, so *d
returns the original element being pointed to. Conversely, (*d)++
just increments the value being pointed to.
Example:
// Case 1
int array[2] = {1, 2};
int *d = &array[0];
int x = *d++;
assert(x == 1 && d == &array[1]); // x gets the first element, d points to the second
// Case 2
int array[2] = {1, 2};
int *d = &array[0];
int x = (*d)++;
assert(x == 1 && d == &array[0] && array[0] == 2);
// array[0] gets incremented, d still points there, but x receives old value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With