不能使用++,C语言中的空指针算术运算符

问题描述 投票:0回答:2

我正在使用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作为减量操作数。

但是(int *)ptr2 +1确实有效。谁能解释为什么会这样?

c pointers void
2个回答
0
投票

++运算符需要一个左值作为操作数,其副作用是更新该值指定的存储位置中存储的值。

强制转换的结果不是左值,没有关联的存储位置存储int *值。您可以将其称为临时值。因此++无法应用于它。


0
投票

强制转换的结果不是左值。 ISO C11的6.5.4 Cast operators部分中有一个脚注,指出:

强制转换不会产生左值。因此,强制转换为限定类型与强制转换为非限定类型具有相同的效果。

类似地,在6.5.3.1 Prefix increment and decrement operators中,(我强调):

前缀递增或递减运算符的操作数应具有原子,限定,或不合格的实数或指针类型,并且应为可修改的左值。

因此,您尝试执行的操作无效。

© www.soinside.com 2019 - 2024. All rights reserved.