V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
amiwrong123
V2EX  ›  程序员

为什么指针的临时变量会报错 lvalue required as increment operand

  •  
  •   amiwrong123 · 21 天前 · 706 次点击
    #include <stdio.h>
    
    int main() {
        char arr[10] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
        char *d = arr;
    
        char value1 = *(((char*)d)++);//这里会报错
        d = arr;
        char value2 = *((char*)d++);
    
        printf("value1: %c, value2: %c\n", value1, value2);
    
        return 0;
    }
    
    gcc test.c -o test
    test.c: In function ‘main’:
    test.c:8:31: error: lvalue required as increment operand
        8 |     char value1 = *(((char*)d)++);
          | 
    

    可能我对编译和 c 这块不是很懂,这个左值不是 c++的概念吗,怎么我这么编译还能报错啊?

    然后就是这个报错信息没看懂,((char*)d)我这样写的,所以就是它就是一个左值了?

    求各位大佬解答一下。

    8 条回复    2024-05-31 12:33:43 +08:00
    hello2090
        1
    hello2090  
       21 天前 via iPhone
    不太记得 C++了,但是 ((char*)d)++ 看起来怪怪的,我猜你写成+1 没问题?
    amiwrong123
        2
    amiwrong123  
    OP
       21 天前
    @hello2090 #1
    写成+1 没问题?

    是的,不会报错的。我只是在想,为啥这样写会报错。
    XiaoxiaoPu
        3
    XiaoxiaoPu  
       21 天前   ❤️ 1
    type cast 产生的是 r-value ,因此 ((char*)d) 是 r-value 。++ 运算符需要 l-value, 所以会报错。
    chenyu0x00
        4
    chenyu0x00  
       21 天前   ❤️ 1
    因为++运算符会修改 d 的值,而((char*)d)看起来被识别为了右值,只能读不能修改,所以就报错了。
    1 楼的换成+1 没问题是因为+1 不会修改值,所以((char*)d)被被识别为了右值也没问题。
    value2 那里没有出问题我猜是先计算了++运算,表达式变成了这样:*( (char*)(d++) )
    amiwrong123
        5
    amiwrong123  
    OP
       21 天前
    @XiaoxiaoPu #3
    OK ,大概理解了。还有个问题,我这不是纯 c 编译吗,怎么还有左值右值的概念。

    我一直以为只有 c++有左值右值的概念。

    原来纯 c 也有啊
    aresyang
        7
    aresyang  
       20 天前
    @amiwrong123 抽象机器 locate 值
    cnbatch
        8
    cnbatch  
       20 天前   ❤️ 1
    左值右值的概念在 C++出现前就已经在纯 C 当中存在了:

    https://www.stroustrup.com/terminology.pdf
    引用开头一段话:
    The terms “lvalue” and “rvalue” are deep in C++’s genes. They were introduced by Christopher Strachey for CPL [Strachey,196?]

    还有

    Dennis Ritchie used “lvalue” to describe C (e.g. see [K&R,1978]), but left out “rvalue”, considering “lvalue” and “not lvalue” sufficient.
    此时 C 语言发明者并未直接使用“右值”这个说法,而是讲“非左值”
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3192 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 11:21 · PVG 19:21 · LAX 04:21 · JFK 07:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.