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

时间:2009-10-10 18:46:10

标签: c pointers

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

6 个答案:

答案 0 :(得分: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.

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

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

while(*second++ = *first++)
{
 // nothing goes here :)
}

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

答案 1 :(得分:9)

增量++具有比解除引用*更高的运算符优先级,因此*d++将指针d递增以指向数组中的下一个位置,但结果++的{​​{1}}是原始指针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

答案 2 :(得分:1)

在官方C术语中,这些表达式确实为您提供了相同的结果。在适当的术语中,非void表达式的“结果”是表达式求值的结果。您的两个表达式都会计算为*d的初始值,所以结果是相同的。

然而,在C中的每个表达式的“结果”中添加零个或多个所谓的“副作用”。这两种表达方式的副作用完全不同。第一个表达式增加指针'd'的值。第二个表达式增加'* d'的值(指向的值)。

答案 3 :(得分:0)

第一个递增指针,第二个递增指向的值。

作为实验,试试这个:

int main() {
    int x = 20;
    int *d = &x;
    printf("d = %p\n", d);
    int z = (*d)++;
    printf("z = %d\n", z);
    printf("d = %p\n", d);
    int y = *d++;
    printf("y = %d\n", y);
    printf("d = %p\n", d);
}

答案 4 :(得分:0)

它们会返回相同的结果,但程序中的状态更改完全不同。

如果我们只是扩展操作,这是最容易理解的。

x = *d++;
// same as
x = *d;
d += 1; // remember that pointers increment by the size of the thing they point to

x = (*d)++;
// same as
x = *d;
*d += 1; // unless *d is also a pointer, this will likely really just add 1

答案 5 :(得分:-1)

我没有编译器方便。

a = (*d)++;
b = (*d);

是== b?我认为不是。