Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between *d++ and (*d)++ in C?

Tags:

c

pointers

as in the title, what's the difference because these two seem to get me the same results?

like image 622
goe Avatar asked Oct 10 '09 18:10

goe


2 Answers

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!

like image 188
Khaled Alshaya Avatar answered Oct 26 '22 13:10

Khaled Alshaya


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
like image 32
Adam Rosenfield Avatar answered Oct 26 '22 14:10

Adam Rosenfield