c - C 中指针的地址不匹配

标签 c pointers

我在理解 C 中整数指针的正确功能方面遇到了一些困难。在 Code-1 中,一切看起来都很好,显然我认为我理解指针。但在代码二中,输出让我担心。众所周知,指针存储的是它们所指向的变量的地址,那么在Code-2中为什么LINE-1和LINE-2的输出不同呢? 为什么Code-2中指针的值和变量的地址不匹配?

代码1

#include <stdio.h>

int main()
{
    int x = 4, *p;

    p = &x;             // adress of x becomes value of pointer p, referencing operator 
    printf("%p\n", p);  //LINE-1// value of pointer, it will be the address of variable 
    printf("%p\n", &x); //LINE-2// address of variable
    printf("%p\n", &p); //LINE-3// address of pointer
    printf("%d\n", *p); //LINE-4// value of variable to which pointer points, deferencing operator

    return 0;
}

代码 1 的输出:-

0x7ffe97df9fec
0x7ffe97df9fec
0x7ffe97df9ff0
4

代码2

#include <stdio.h>

int main()
{
    int x = 4, *p;

     *p = x;             // 
     printf("%p\n", p);  //LINE-1// value of pointer, it will be the address of variable 
     printf("%p\n", &x); //LINE-2// address of variable
     printf("%p\n", &p); //LINE-3// address of pointer
     printf("%d\n", *p); //LINE-4// value of variable to which pointer points, dereferencing operator

     return 0;
}

代码2的输出:-

0x7ffd370c17d0
0x7ffd370c16dc
0x7ffd370c16e0
4

最佳答案

在“代码 2”中,p 从未被赋值。

因此,通常不知道*p = x会做什么。该表达式通常将x 的值存储在p 指向的位置。但是因为 p 从未被赋值,所以我们不知道 p 指向哪里,或者它是否指向任何地方,并且 C 标准没有定义该行为。

当您在未分配值的情况下打印 p 时,程序可能会打印分配给 p 使用的内存中的任何内容,或者它可能打印了从某个处理器寄存器中发生的任何事情获得的垃圾,或者其他东西 - 无论发生什么本质上只是编译器的特性,而不是定义的行为。

关于c - C 中指针的地址不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47244141/

相关文章:

c - C 中的管道标准输出

CMSIS FIR 带通滤波器

c - 高效读取映射数据内存

c - 为什么 malloc 使用零大小?

c - 当你有一个类型(char)一个指针(*)和一个 const 关键字时如何解释声明?

c - 在 C 中获取垃圾值的原因

c++ - 对话框关闭时 Win32 应用程序立即退出

pointers - 垃圾收集与共享指针

c - 我无法理解这个程序的输出

c - 从指针赋值给变量失败