c - 为什么编译器不生成错误 "lvalue required"?

标签 c pointers lvalue

根据我的理解,在下面代码中标记为“第 2 行”的行中,表达式 (*ptr)++ 应该生成“需要左值”错误,因为 *ptr 的计算结果为 i=1 的常量值,这不是左值?

那么为什么程序能成功运行呢?还是我的概念有问题?如果是,请赐教。

int main(void)
{
    int i;
    int *ptr = (int *) malloc(5 * sizeof(int));

    for (i=0; i<5; i++)
        *(ptr + i) = i;

    printf("%d ", *ptr++);   //line 1
    printf("%d ", (*ptr)++); //line 2 
    printf("%d ", *ptr);     //line 3
    printf("%d ", *++ptr);   //line 4
    printf("%d ", ++*ptr);   //line 5
}

最佳答案

你误会了。 (*ptr) 的结果 左值,可以在其上应用后增量运算符。

所以,在你的情况下,

 printf("%d ", (*ptr)++); //line 2

很好。

引用 C11 标准,第 6.5.3.2 章,地址和间接运算符(强调我的)

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object.

FWIW,如果 *ptr 不是左值,您也会因为编写类似 *ptr = 5 的内容而出错,不是吗?

关于c - 为什么编译器不生成错误 "lvalue required"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31398970/

相关文章:

c - 为什么这个宏被定义为({ 1; })?

创建多个文件并用 C 链接它们

c - 二进制搜索树插入抛出段错误

c - 使用指针操作打印输入的字符串

c - C 中指针的区别

c - 需要左值 : error in c

c - 数组名称不是左值是否有原因?

c - "ld returned 1 exit status"和 "incompatible implicit declaration of built-in function ' 退出 ' "

C++ 函数总是返回相同的指针

c++ - 表达式 `new T` 的计算结果是右值还是左值?