【问题标题】:I can't understand his typedef with pointer usage, can someone explain?我无法理解他的 typedef 指针用法,有人可以解释一下吗?
【发布时间】:2020-06-27 19:02:19
【问题描述】:

前段时间我有一个学校项目,当时我正在学习 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

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

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

非常感谢大家的帮助!!

【问题讨论】:

  • Parcel 是什么。
  • *(*cartography + idx) 看起来不对。乍一看,它应该是 *(cartography + idx) 或等价的 cartography[idx]
  • @pmg 如果 Parcel 也是一个指针。所以不一定 - 但在没有显示包裹无法回答的情况下提出问题
  • 它是由你的老师写的或用作示例程序 - 太可怕了。最糟糕的 C 实践之一 - 将指针隐藏在 typedef 中。
  • @P__J__ 这公认的智慧,是的,但是当我第一次使用指针时,使用指针编写可编译代码更容易 typedef,这让我开始了。这不是隐藏的问题,而是便利的问题。当我对指针变得更满意时,我就放弃了。我们不要低估初学者在 C 语言中使用指针所遇到的困难。

标签: c pointers typedef


【解决方案1】:

嗯,贴出来的代码有点混乱……

您为具有“typedef”的结构创建了一个新类型 Parcel。

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

从现在开始,您可以使用 Parcel 进行制图,如下所示。

Parcel *Cartography;

这是我认为合理的方式......

另外,我想告诉你我对指针*操作的理解。
指针运算符 * 用于在声明指针时指定指针的名称。 然后 * 用来指向指针所指向的值。

如果您将 Cartography 声明为指向 Parcel 的指针,则 malloc 的返回值应分配给指针 Cartography,而不是指向的值 *Cartography。

我认为您正在尝试处理多个 Parcel,然后您可以使用指针数组或指向 Parcel 的指针。

我希望这可以帮助您找到线索...

【讨论】:

    【解决方案2】:

    您不使用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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多