我的 CS 课程正在从 Java 转向 C。我现在正忙于查看指针,我发现用于递增的 ++ 运算符在取消引用时不起作用。这更像是一个好奇的问题。只是还不习惯指针的概念。我只是做错了什么还是与指针有关?
例如:
*pointer++; Will not increment the value.
*pointer+=1; Will increment the value.
提前致谢!
当您想增加值时,您必须确保使用括号。
(*pointer)++;
*pointer++
增加pointer
变量,而不是它指向的值。
int array[4] = {3,5,7,9};
int *pointer = array;
// *pointer equals 3
*pointer++;
// *pointer now equals 5
*pointer++;
相当于
*(pointer++); // pointer is incremented
而不是
(*pointer)++; // pointee is incremented
*pointer++;
几乎等同于:
*pointer;
pointer = pointer + 1;
为什么会这样?
在表达式*pointer++;
中,++
是后缀运算符,因此执行第一个*
遵循操作然后++
递增值pointer
(而不是递增值)。
而 *pointer += 1
仅相当于:
*pointer = *pointer + 1;
增加 指向的值pointer
。
这与运算符的优先级有关:后增量++
比取消引用运算符具有更高的优先级*
,而在运算符优先级表中+=
具有较低的优先级。这就是为什么在第一个示例中应用于随后被取消引用的指针,而在第二个示例中应用于取消引用的结果。++
+= 1