不能对指针运算的结果使用 ++、-- 运算符
Cannot use ++, -- operator on the result from pointer arithmetic
我正在使用 VS Code 和 GCC 编译器。
这是代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
void *ptr = malloc(100);
printf("%p\n", ptr);
printf("%p\n", (int *)ptr + 1);
printf("%p\n", (int *)ptr - 1);
void *ptr2 = ptr;
printf("%p\n", (int *)ptr2 + 1); // Works well
printf("%p\n", ++(int *)ptr2); // error: lvalue required as decrement operand
free(ptr);
return 0;
}
当我编译上面的代码时,++(int *)ptr2
得到错误:"lvalue required as decrement operand"。
但是,(int *)ptr2 + 1
确实有效。
谁能解释为什么会这样?
++
运算符需要一个左值作为操作数,它的副作用是更新存储在该值指定的内存位置的值。
转换的结果不是左值,没有存储 int *
值的关联内存位置。您可以将其称为临时值。所以++
不能应用于它。
转换的结果不是左值。 ISO C11 的 6.5.4 Cast operators
部分中有一个脚注指出:
A cast does not yield an lvalue. Thus, a cast to a qualified type has the same effect as a cast to the unqualified version of the type.
同样,在6.5.3.1 Prefix increment and decrement operators
中,它指出(我的重点):
The operand of the prefix increment or decrement operator shall have atomic, qualified,
or unqualified real or pointer type, and shall be a modifiable lvalue.
因此,您尝试执行的操作无效。
(int *)ptr2 + 1
起作用的原因是因为 ptr2
是 一个左值,所以它可以被强制转换。添加 1
是对转换值完成的,这也是有效的。
您正在尝试的情况与 ++(ptr+1)
之类的情况没有什么不同,后者是尝试递增非左值的 不同 方式。这是因为你的演员表和表达式 ptr+1
都是 短暂的 对象,只需要存在足够长的时间以用于立即操作(加法或演员表,不是预增量)。
如果您稍微重新设计事情的完成方式,您的问题就会消失(因为 void*
可以自由地与大多数其他指针进行转换):
printf("%p\n", ptr2 = ((int*)ptr2) + 1);
我正在使用 VS Code 和 GCC 编译器。 这是代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
void *ptr = malloc(100);
printf("%p\n", ptr);
printf("%p\n", (int *)ptr + 1);
printf("%p\n", (int *)ptr - 1);
void *ptr2 = ptr;
printf("%p\n", (int *)ptr2 + 1); // Works well
printf("%p\n", ++(int *)ptr2); // error: lvalue required as decrement operand
free(ptr);
return 0;
}
当我编译上面的代码时,++(int *)ptr2
得到错误:"lvalue required as decrement operand"。
但是,(int *)ptr2 + 1
确实有效。
谁能解释为什么会这样?
++
运算符需要一个左值作为操作数,它的副作用是更新存储在该值指定的内存位置的值。
转换的结果不是左值,没有存储 int *
值的关联内存位置。您可以将其称为临时值。所以++
不能应用于它。
转换的结果不是左值。 ISO C11 的 6.5.4 Cast operators
部分中有一个脚注指出:
A cast does not yield an lvalue. Thus, a cast to a qualified type has the same effect as a cast to the unqualified version of the type.
同样,在6.5.3.1 Prefix increment and decrement operators
中,它指出(我的重点):
The operand of the prefix increment or decrement operator shall have atomic, qualified, or unqualified real or pointer type, and shall be a modifiable lvalue.
因此,您尝试执行的操作无效。
(int *)ptr2 + 1
起作用的原因是因为 ptr2
是 一个左值,所以它可以被强制转换。添加 1
是对转换值完成的,这也是有效的。
您正在尝试的情况与 ++(ptr+1)
之类的情况没有什么不同,后者是尝试递增非左值的 不同 方式。这是因为你的演员表和表达式 ptr+1
都是 短暂的 对象,只需要存在足够长的时间以用于立即操作(加法或演员表,不是预增量)。
如果您稍微重新设计事情的完成方式,您的问题就会消失(因为 void*
可以自由地与大多数其他指针进行转换):
printf("%p\n", ptr2 = ((int*)ptr2) + 1);