【问题标题】:Pointer arithmetic in C not pointing to the correct variables if I don't print the address of the variables如果我不打印变量的地址,C 中的指针算术不会指向正确的变量
【发布时间】:2021-12-10 03:21:25
【问题描述】:

所以我正在做指针算术作业,我需要按照预期的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

【问题讨论】:

  • 当事物的地址未被引用时,它们可能没有地址。通常,也不能保证函数的堆栈框架中的事物是如何排序的。
  • 你不能把局部变量当作一个数组,这不是事情的运作方式。它导致未定义的行为并使您的程序格式错误。无论你从哪里学到这一点,都应该把它扔掉。
  • 另外,请不要发布文字图片。复制粘贴文本作为文本。也请花一些时间阅读the help pages,阅读SO tour,阅读How to Ask,以及this question checklist
  • 这是我大学计算机科学课程的一部分,目前我正在询问是否允许将变量转换为数组。此外,我很确定如果我使用的是我学校推荐的 TurboC,这会起作用,尽管我确实可以使用 vscode

标签: c gcc


【解决方案1】:

所以我知道逻辑可行,但如果不先打印就行不通

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


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

ptr &gt;= &amp;a未定义的行为 (UB)。

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

ptr-- 也是 UB,因为它试图在d 之前形成地址。指针数学只适用于数组/对象(或之后)

【讨论】:

  • 在 OP 的情况下,我怀疑缺少 printf("%p\n",(void*)&amp;c); printf("%p\n",(void*)&amp;b); 只是优化了 b, c,因为它们没有被使用。仍然 ptr &gt;= &amp;a 仍然是 UB。
【解决方案2】:

您的程序有四个不同的变量,而不是大小为 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;
}

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多