gpt4 book ai didi

c - 即使在增加地址后,指针的值如何相同,对于变量来说它是不同的

转载 作者:行者123 更新时间:2023-12-02 09:07:58 24 4
gpt4 key购买 nike

在下面的程序中,我为不同的指针操作获得相同的值:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>

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

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

printf("%d ", *ptr++);
printf("%d ", (*ptr)++);
printf("%d ", *ptr); ---------> o/p: 2
printf("%d ", *++ptr);--------> o/p: 2
printf("%d ", ++*ptr);
}

输出:0 1 2 2 3

我的疑问是 *ptr*++ptr 如何打印相同的值。当我们增加指针地址时,它应该会有所不同

变量的后自增和前自增我能理解,这里都是前自增

最佳答案

使用 (*ptr)++),您可以增加 ptr 指向的值,这样您的“数组”就包含两个相等的值,即 ptr[0]==2ptr[1]==2。这就是为什么 *ptr*++ptr 产生相同的值,尽管它们指向不同的地址。

删除printf("%d ", (*ptr)++),你会看得更清楚。

关于c - 即使在增加地址后,指针的值如何相同,对于变量来说它是不同的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55701452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com