【问题标题】:dereferencing pointer to incomplete type - typedef struct [closed]取消引用指向不完整类型的指针 - typedef struct [关闭]
【发布时间】:2016-09-05 20:34:42
【问题描述】:

我正在寻找我的代码中的错误(在 C 中),但我没有找到任何东西。 我查看了许多博客并尝试了许多建议但没有任何帮助的方法。
我已经编码了:

typedef struct Account_t *Account;
struct Account_t {
     Customer customer;
     Realtor realtor;
     Offer offer;
};

而 Realtor、Customer 和 Offer 已明确定义并包含在 .h 文件中。我收到一条错误消息,提示“取消引用指向不完整类型 'struct Account_t' 的指针”:

 Account account = malloc(sizeof(*account));

请帮我找出问题!

【问题讨论】:

  • 这应该是有效的(见here)。请发布一个完整的示例。出于某种原因,编译器在您使用 malloc 时没有看到结构定义。
  • 显示CustomerRealtorOffer的定义。
  • ...而 Realtor、Customer 和 Offer 定义明确...您可以将它们包含在您的帖子中吗?

标签: c database struct error-handling typedef


【解决方案1】:

我试用了您的代码。我和你有类似的问题。

问题在于您的代码,当您在堆中分配结构时,返回的值分配错误,因为 malloc 返回一个指针。

我的代码如下所示:

Account* account = (account*)malloc(sizeof(account));

第二件事: 作为类型定义,我没有将结构定义为指针。

typedef struct account_t Account;

试试这个,希望这些信息有用!

【讨论】:

    【解决方案2】:

    编译问题,应该通过正确的类型转换和正确的类型分配来处理。考虑到 Account 被声明为指向 Account_t 的指针,请参见 typedef,正确的 sizeof 应取自 Account_t 或 Account* 或 *account。但指针转换为 Account。
    我会说,你必须这样做:

    Account account = (Account)malloc(sizeof(*account));
    

    【讨论】:

    • sizeof(account) 将返回指针的大小(8 或 4 字节)。 sizeof(*account) 将返回 sizeof(Account_t)
    • 事实上这正是本意。发布问题的用户没有明确提出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多