C中的*d ++和(*d)++有什么区别?

goe*_*goe 8 c pointers

在标题中,有什么区别,因为这两个似乎得到了相同的结果?

Ara*_*raK 13

不,他们不一样.假设这d是一个指向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.
Run Code Online (Sandbox Code Playgroud)

我认为在K&R中有一个例子,我们需要将c-string复制到另一个:

char* first = "hello world!";
char* second = malloc(strlen(first)+1);
....

while(*second++ = *first++)
{
 // nothing goes here :)
}
Run Code Online (Sandbox Code Playgroud)

代码很简单,将指向的字符放入指向first的字符中second,然后在表达式增加两个指针.当然,当复制的最后一个字符是'\ 0'时,表达式会导致false并停止!

  • @Jørgen:C的创造者怎么能用坏的风格写C代码?根据定义,这是在C中完成的. (2认同)

Ada*_*eld 9

增量++具有比取消引用更高的运算符优先级*,因此*d++将指针递增以指向d数组中的下一个位置,但结果++是原始指针d,因此*d返回指向的原始元素.相反,(*d)++只是递增指向的值.

例:

// 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
Run Code Online (Sandbox Code Playgroud)