linux c shared memory:why 读写时内容顺序相反

linux c shared memory:why the order of contents are opposite when write and read

我想在共享内存中使用 int 数组,在将 1,2,3 写入其中后,我希望它像 this:1,2,3.But 我读 this:3, 2,1.I不知道为什么

write code:
int *gIn;
int main(){
    int id;
    id = shmget(0x666,1024,IPC_CREAT|0666);
    gIn=(int *)shmat(id,NULL,0);

    *gIn++=10;
    *gIn++=20;
    *gIn++=30;
    sleep(10);
    return 0;
}

read code:
int *gIn;
int main(){
    int id;
    id = shmget(0x666,1024,IPC_CREAT|0666);
    gIn=(int *)shmat(id,NULL,0);

    printf("%d|%d|%d\n",*gIn++,*gIn++,*gIn++);
    return 0;
}

我预计读取过程的输出是10|20|30,但实际输出是30|20|10.It非常strange.I不知道为什么

问题出在这一行:printf("%d|%d|%d\n",*gIn++,*gIn++,*gIn++);printf 的参数的评估顺序是实现定义的。在您的情况下,它恰好按照您没有预料到的顺序执行此操作。

建议你把局部变量(或数组)中printf前的值单独取出来打印出来