首页 > 解决方案 > 我无法理解他的 typedef 指针用法,有人可以解释一下吗?

问题描述

前段时间我有一个学校项目,当时我正在学习 C,但现在已经有一段时间无法如此轻松地理解指针了。代码如下:

    typedef struct {
     Identification id;
     Ring edge;
     Ring *holes;
     in nHoles;
    } Parcel;

    typedef Parcel *Cartography;
    //this is the definition of Cartography
    
    
    
    *cartography = malloc(sizeof(Parcel));
    
    *(*cartography + idx) = readParcel(f);
    //this is the code when I want to insert a new Parcel into Cartography

我不明白为什么在尝试添加新包裹时必须使用“ *” 2次,有人可以向我解释一下吗?

是因为制图学中的值是 malloc 的地址,所以第一个 * 给了我那个地址,第二个 * 把我带到那个地址?

非常感谢大家的帮助!!

标签: cpointerstypedef

解决方案


你不用 . 声明变量typedef。此外,您不应将返回的指针分配给malloc()非指针类型。Cartography是一个指针类型,并且取消引用它*意味着您将指针分配给Parcel. 这是正确的代码:

typedef struct {
 Identification id;
 Ring edge;
 Ring *holes;
 in nHoles;
} Parcel;

Parcel *Cartography;
//this is the definition of Cartography



Cartography = malloc(sizeof(Parcel));

*(Cartography + idx) = readParcel(f);

推荐阅读