2

我的 CS 课程正在从 Java 转向 C。我现在正忙于查看指针,我发现用于递增的 ++ 运算符在取消引用时不起作用。这更像是一个好奇的问题。只是还不习惯指针的概念。我只是做错了什么还是与指针有关?

例如:

*pointer++; Will not increment the value.
*pointer+=1; Will increment the value.

提前致谢!

4

5 回答 5

5

当您想增加值时,您必须确保使用括号。

(*pointer)++;
于 2013-07-23T17:57:52.630 回答
4

*pointer++增加pointer变量,而不是它指向的值。

int array[4] = {3,5,7,9};

int *pointer = array;

// *pointer equals 3

*pointer++;

// *pointer now equals 5
于 2013-07-23T17:58:29.470 回答
4
*pointer++;

相当于

*(pointer++);  // pointer is incremented

而不是

 (*pointer)++;  // pointee is incremented
于 2013-07-23T17:58:39.460 回答
2

*pointer++;几乎等同于:

*pointer;
pointer = pointer + 1;

为什么会这样?

在表达式*pointer++;中,++是后缀运算符,因此执行第一个*遵循操作然后++递增值pointer(而不是递增值)。

*pointer += 1仅相当于:

*pointer =  *pointer + 1;

增加 指向的值pointer

于 2013-07-23T17:57:39.160 回答
2

这与运算符的优先级有关:后增量++比取消引用运算符具有更高的优先级*,而在运算符优先级表中+=具有较低的优先级。这就是为什么在第一个示例中应用于随后被取消引用的指针,而在第二个示例中应用于取消引用的结果。+++= 1

于 2013-07-23T17:59:12.160 回答