【问题标题】:Setting Struct equal to a function that returns the same struct将 Struct 设置为返回相同结构的函数
【发布时间】:2012-02-29 15:04:50
【问题描述】:

所以我在我的项目的最后一步,我必须从一个函数中返回一个结构,所以我可以在 main.js 中使用它。 相关代码可见:

typedef struct SomeProduct {
    int itemNum;
    char itemName[21];
    double unitPrice;
    int stockQty;
    int restockQty;
    struct SomeProduct *next;
} SProduct;

 struct llpro {

 SProduct data;
 struct llpro *next;
 };

////////////////////SKIP LINES to identifier

SProduct findItem(struct llpro *head,int num);

///////////////////SKIP LINES to assignment that fails. head is the proper
////////////////// pointeritemspurchased is an int.

SProduct steve;
steve=findItem(head,newv.itemsPurchased[y]);

//////////////////Skip Lines to method

SProduct findItem(struct llpro *head,int num)
{
    while(head!=NULL)
    {
       if(head->data.itemNum==num)
       {
         SProduct paul;
         paul=head->data;
         return paul;
       }
    }
}

每当我尝试编译它时,我都会收到链接器错误,说它们从未定义过。然后当我取出标识符时,我收到一条消息说 steve 和 paul 是不兼容的类型,即使它们都是 SProducts。请帮忙! 我还想澄清一下,我试图做的是搜索 Sproducts 的链接列表,并从与我正在搜索的那个共享项目编号的那个中提取信息。链接器错误显示“函数 printsum 中对 'findiem' 的未定义引用

【问题讨论】:

  • 您也可以添加错误吗?此外,如果head 不是NULL,则findItem 中的循环是无限的;原因是你永远不会改变head
  • 我不确定如何添加它们,但是当代码不包含以下行时: SProduct findItem(struct llpro *head,int num);我收到一条消息,指出分配中的类型不兼容。当我这样做时,我会收到一个说链接器错误
  • 拥有struct llpro 会有所帮助。现在我们需要确定您将steve 分配给paul 的位置,反之亦然。
  • 您确定 SProduct 实际上是在您尝试使用它的范围内定义的吗?也许你忘记了# include 指令。
  • Steve=findItem(....) 是他被分配给 paul 的地方,因为 paul 被归还。对吗?

标签: c struct variable-assignment


【解决方案1】:

此代码在 GCC 4.1.2 下编译,带有选项 -Wall -Wextra -std=c99:

#include <stddef.h>

typedef struct SomeProduct
{
    int                 itemNum;
    char                itemName[21];
    double              unitPrice;
    int                 stockQty;
    int                 restockQty;
    struct SomeProduct *next;
} SProduct;

struct llpro
{
    SProduct data;
    struct llpro *next;
};

SProduct findItem(struct llpro *head,int num);

int main(void)
{
    struct llpro *head = 0;
    SProduct steve;
    steve = findItem(head, 1);
}

SProduct findItem(struct llpro *head, int num)
{
    while (head != NULL)
    {
        if (head->data.itemNum == num)
        {
            SProduct paul;
            paul = head->data;
            return paul;
        }
    }
    SProduct alan = { 0, "", 0.0, 0, 0, 0 };
    return alan;
}

主要更改是使用1 代替findItem() 的参数的复数值,并在findItem() 的末尾添加return。两者都不会影响任何分配。

所以,假设你有问题,你错误地摘录了你的代码,没有向我们展示导致问题的行。

【讨论】:

  • Jonathan 我可以通过电子邮件将我的实际代码发送给您吗?就像我说的,我不能在网上发布。它将是未经编辑的,我认为更多的用途。
  • 查看实际代码,函数findItem()在使用前没有声明,实际实现嵌套在另一个函数中,在使用点之后。
  • 问题已更新以包含信息链接器错误显示“undefined reference to 'finditem' in function printsum。这表明您写的是“finditem”而不是“findItem”; C 区分大小写。 (它还建议您省略关键代码,这显然是函数printsum。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 1970-01-01
  • 2019-08-28
  • 1970-01-01
  • 2018-08-04
  • 2017-08-30
相关资源
最近更新 更多