Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a struct passed as a pointer - C

Tags:

c

function

struct

I'm trying to modify a struct that was passed as a parameter by using a pointer by I can't get it working. I cant just return the struct because the function must return an integer. How can I modify the struct in the function? This is what I've done so far:

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;
    }


}

I get this error: "error: request for member: 'act_quantity' in something not a structure or union' " in all the lines where I tried to modify the struct.

EDIT: I had used "." instead of "->". I fixed it now. It still gives me an error: " invalid type argument of unary '*' (have 'int')"

like image 940
Arlind Avatar asked Jul 23 '26 06:07

Arlind


2 Answers

Operator Precedence causes

*article.act_quantity

to be interpreted as *(article.act_quantity)

It should be (*article).act_quantity or article->act_quantity (when the LHS is a pointer)

like image 50
Suvarna Pattayil Avatar answered Jul 26 '26 11:07

Suvarna Pattayil


When you reference a pointer to a structure you need either

article->act_quantity

or

(*article).act_quantity
like image 44
Sodved Avatar answered Jul 26 '26 10:07

Sodved



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!