如果我不打印变量的地址,C 中的指针算法不会指向正确的变量

Pointer arithmetic in C not pointing to the correct variables if I don't print the address of the variables

所以我正在做指针算术作业,我需要按预期使用它递减和递增指针 outcome。这就是我所做的

#include <stdio.h>

void main(void){
    int d = 10;
    int c = 8;
    int b = 6;
    int a = 4;

    int *ptr; //these lines are given

    printf("decrement \n");
    for (ptr = &d; ptr >= &a; ptr--)
    {
        printf("%d \n",*ptr);
    }

    printf("increment \n");
    for (ptr = &a; ptr <= &d; ptr++)
    {
        printf("%d \n",*ptr);
    }
}

但结果跳过了 8 和 6:

decrement
10
4
increment
4
10

所以我决定打印开头的地址以帮助调试

    printf("%p\n",(void*)&d);
    printf("%p\n",(void*)&c);
    printf("%p\n",(void*)&a);
    printf("%p\n",(void*)&b);

但在 运行 之后,它就可以正常工作了

000000fc6a9ffb34
000000fc6a9ffb30
000000fc6a9ffb28
000000fc6a9ffb2c
decrement
10
8
6 
4
increment
4
6
8
10

所以我知道逻辑是可行的,但如果不先打印它就行不通,我不知道为什么

我正在使用 Vscode 和 GCC

So I know that the logic works out, but it just doesn't work without printing first

未定义的行为 (UB),任何事情都可能发生。


int d = 10;
int a = 4;
int *ptr = &d; 
    ptr >= &a

ptr >= &a 未定义的行为 (UB)。

C 中指针的顺序比较在不属于同一数组(或后一个数组)时是 UB。

ptr-- 也是 UB,因为它试图在 d 之前形成地址。指针数学仅在 array/object(或之后)

内有效

您的程序有四个不同的变量,而不是大小为 4 的数组。所以变量的地址是不可预测的。

    int d = 10;
    int c = 8;
    int b = 6;
    int a = 4;

在数组中内存是连续分配的,所以如果你想这样做就使用数组。

#include<stdio.h>
int main(){
    int arr[4] = {1, 2, 3, 4};
    // increment
    for(int i=0; i<4; i++)
        printf("%d\n",*(arr + i));
    // decrement
    printf("-------------------------------\n");
    for(int i=3; i>=0; i--)
        printf("%d\n",*(arr + i));
    return 0;
}

在您的第一个示例中,您没有使用变量 b 和 c,仅使用 a 和 d - 因此(我怀疑)实施正在优化它们

在第二个示例中,您使用了所有四个变量 a、b、c 和 d,因此无法优化掉它们