首页 > 解决方案 > 为什么我们不能将点用于新创建的指向结构的指针

问题描述

我有点困惑,为什么这段代码有效:

struct product{
    double price;
    int quantity;
    char name[1];
}p2;
printf("%d",p2.quantity);

虽然这不起作用:

struct product *p3=&p2;
printf("%d",p3.quantity);

我的意思是p2p3都是指向同一个对象的指针,所以为什么我们需要printf("%d",p3->quantity);在第二种情况下编写才能让它工作。

标签: cpointersstruct

解决方案


To answer your confusion about C "pointers":

  • C != C#.

  • C doesn't have .Net reference objects.

  • And although you can take the address of any C object (a char, an int, a struct, etc) to turn it into a pointer, that object isn't necessarily itself a pointer.

Look here:

Difference between variable and data object in C language?

In C, an object is anything that takes up storage. C 2011 online draft.

An lvalue is an expression that designates an object such that the contents of that object may be read or modified (basically, any expression that can be the target of an assignment is an lvalue). While the C standard doesn't define the term variable, you can basically think of it as any identifier that designates an object...

A pointer is any expression whose value is the location of an object. A pointer variable is an object that stores a pointer value.


推荐阅读