*p 包含什么?

what does *p contain?

根据多个来源,指针 p 在取消引用时指向一个值。因此,我们可以说指针包含一个地址作为它的值,当使用解引用运算符 (*) 时,返回地址 处的值

一个指针可以被赋值如下:

int a = 90; int *p = &a;

如果我们分配一个指针,它的值如下:

int *p; *p = 60;

60 分配给 p 并在取消引用时导致未定义的行为,因为 60 不是有效地址。 (根据 the answer to this question)。

但是,对于下面的代码:

    int a = 90;
    int *p = &a;

    printf ("p is %d \n",*p);
    printf ("a is %d \n", a);
    printf ("address is %p \n",p);

    *p = 100;

    printf ("p is %d \n",*p);
    printf ("a is %d \n", a);   
    printf ("address is %p \n",p);

收到以下输出:

p is 90
a is 90
address is 0028FED8

p is 100
a is 100 address is 0028FED8

即,表达式 *p = 100 更改 a 处的值,而不是 p 包含的值。

怎么做?????

As per multiple sources, a pointer p points to a value when it is dereferenced.

不完全是。指针指向一个对象。取消引用指针会生成该对象。在需要值的上下文中使用对象会生成存储值。

int *p = &a;

p现在指向的对象是a

*p = 100;

取消引用 p 生成指向的对象,即 a。由于这不是需要存储值的上下文,因此不会读取 a 的值,它仍然是对象 a,它被分配了值 100.

或者,简单地说,*p表示a,因此*p = 100表示a = 100

*p = &a 甚至无法编译。 p 是指向 int 的指针。它目前有一个未定义的值,因此将任何东西分配给 *p 都是未定义的行为,很可能会崩溃。但是,即使 p did 指向一个 int,你也只能将一个 int 赋值给 *p,&a 是一个指向 int 的指针,而不是一个 int,所以这不会编译。

在您的第二个示例中,*p = 60,p 的值未定义,因此您试图将 60 存储到内存中未定义的位置。瞬间崩溃。 p 没有被这个修改,所以你的解释是错误的。 p 未设置为 60。您不能将 p 设置为 int。您只能将其设置为指向 int 的指针。

正确:

p = &a; 
*p = 60;

您曾问过:

ie, the expression *p = 100 changes the value at a, and not the value contained by p.

您可以阅读评论部分以了解每一行 C 代码的解释,我没有使用确切的地址位置,而是使用任意地址来进行演示:

int *p;       // Stack variable pointer to integer type w/ p's address being 4 bytes      @  0x00000000
int a = 90;   // Stack integer variable `a` and initializing it to the value of 90 located @  0x00000040 
*p = &a;      // Dereferencing the pointer `p` to be equal to the address of `a` ... One would think
              // that the address value of `a` 0x00000040 in hex would be stored into `a` which
              // has the value of 64 in decimal, however this is not always the case and this should be 
              // undefined behavior, but can still compile and run depending on the compiler and architecture. 
              // It may run or crash or not even compile or build at all. Most compilers should throw an error.

*p = 100;    // 'p' is located at 0x00000000 and contains the value 0x00000040 and by dereferencing it
             // it will assign the value of 100 to the stack address location of 0x00000040. Thus this
             // changes the value of `a` to 100

             // These two statements are in a sense equivalent  
*p = 100;    a = 100;
             // If one was to assign the address of `a` to `p` as such:
 p = &a;

编辑

            // Therefor the statement `*p=100` will only work if the statement
            // `p=&a` is defined and evaluated beforehand.

编辑 现在关于基于标题的问题:"what does *p contain?" 提供了操作的原始代码 *p 实际上包含垃圾或在声明时分配给它的内容。

开头你写的代码:

int *p;
int a = 90;
*p = &a;

无效,第 1 行中的星号 (*) 表示它是一个指针,它不是第 3 行中的解引用运算符。

以下代码:

int a = 90;
int *p = &a;

相当于:

int a = 90;
int *p;
p = &a;

(p) 是一个指针,现在指向 (a)

的地址
*p = 100;

因此,您只需为 a 赋值,a = 100。 并且您正在从同一地址打印相同的值。