【问题标题】:Typedef struct pointer to another typedef structTypedef struct 指向另一个 typedef 结构的指针
【发布时间】:2014-11-29 07:23:02
【问题描述】:

我对这段代码有一些问题:

typedef struct Product {

    char product_code[5];
    int sells;
    int sells_quantity;
}p[3];

typedef struct Seller {
    char seller_code[5];
    Product *ptr;
}seller[5];

为什么它给我一个Product *ptr 的错误?

【问题讨论】:

  • 你为什么要标记这个 C++? C++ 编译器应该可以很好地编译该代码。在 C 中,您需要 struct Product *ptr;
  • 请注意,您的第一个 typedef 定义了一个类型 struct Product(或多或少是偶然的),以及一个类型 p,它是一个由 3 个 struct Product 类型元素组成的数组。同样,您的第二个typedef 尝试定义一个类型seller,它是一个由struct Seller 类型的5 个元素组成的数组。

标签: c struct


【解决方案1】:

你可以尝试替换你的代码

typedef struct Product {

    char product_code[5];
    int sells;
    int sells_quantity;
}p[3];

与

typedef struct Product {

    char product_code[5];
    int sells;
    int sells_quantity;
} Product;               // from here the structure type Product is recognized by the compiler. 

【讨论】:

    【解决方案2】:

    你可以这样做:

    typedef struct Product {
    
    char product_code[5];
    int sells;
    int sells_quantity;
    }p[3],Product;
    
    typedef struct Seller {
      char seller_code[5];
      Product *ptr;
    }seller[5];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多