繁体   English   中英

修改作为指针传递的结构-C

[英]Modifying a struct passed as a pointer - C

我试图通过使用指针修改作为参数传递的结构,但我无法使其正常工作。 我不能只返回该结构,因为该函数必须返回一个整数。 如何修改函数中的结构? 到目前为止,这是我所做的:

typedef enum {TYPE1, TYPE2, TYPE3} types;

typedef struct {
                types type;
                int act_quantity;
                int reorder_threshold;
                char note[100];

}elem;

int update_article(elem *article, int sold)
{
    if(*article.act_quantity >= sold)
    {
        article.act_quantity = article.act_quantity - sold;
        if(article.act_quantity < article.act_quantity)
        {
            strcpy(article.note, "to reorder");
            return -1;
        }
        else
            return 0;
    }
    else if(article.act_quantity < venduto)
    {
        strcpy(*article.note, "act_quantity insufficient");
        return -2;
    }


}

我在尝试修改该结构的所有行中收到以下错误消息:“错误:请求成员:'act_quantity'的内容不是结构或联合”。

编辑:我用过“。” 而不是“->”。 我现在修复了。 它仍然给我一个错误:“一元'*'(具有'int')的无效类型参数”

运算符优先原因

*article.act_quantity

解释为*(article.act_quantity)

它应该是(*article).act_quantityarticle->act_quantity (当LHS是指针时)

当您引用结构的指针时,您需要

article->act_quantity

要么

(*article).act_quantity

*article.act_quantity更改为(*article).act_quantity ,或者将其更改为article->act_quantity等,更好。运算符优先级可将您article->act_quantity这里...

处理指针时,它应该是ptr->member ,而不是ptr.member

这应该解决问题

int update_article(elem *article, int sold)
{
    if(article->act_quantity >= sold)
    {
        article->act_quantity = article->act_quantity - sold;
        if(article->act_quantity < article->reorder_threshold)
        {
            strcpy(article->note, "to reorder");
            return -1;
        }
        else
            return 0;
    }
    else if(article->act_quantity < sold)
    {
        strcpy( article->note, "act_quantity insufficient");
        return -2;
    }
}

您不必返回指向该结构的指针,因为它仍然与输入相同。 您将地址传递给函数,然后使用该地址处的内容。 在这种情况下,无需返回与该结构相关的任何东西

article是一个指针,因此您不能只使用article.act_quantity而应该替换. ->

article->act_quantity

使用箭头运算符通过结构指针访问结构的成员。 但是必须有有效的内存。

这个:

strcpy(*article.note, "act_quantity insufficient");

将不起作用, note是一个字符数组,不能推论它。 你需要:

strcpy(article->note, "act_quantity insufficient");
  • 它仍然给我一个错误:“一元'*'(具有'int')的无效类型参数”

因为您编写的是*article->act_quantity而不是article->act_quantity 修理它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM