Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c-code reference to a struct

I'm a rather experience C++ programmer, but with (pure!?) C-code I am sometimes struggling, especially when I haven't used it in a while. Can someone give me a hint on why the code below is not working? Compiler says:

syntax error : missing ')' before '&'

complaining about the line that has the printItem-signature. How I can make it work? Is the only option to change the printItem-signature to:

void printItem(const struct structItem *const item)
{   
    printf("age: %i, price: %i", item->age, item->price);
}

Or is there another way, that would allow me to keep the signature as it is below? Also, ...I didn't use the more convenient "typedef" notation for the struct, because I remember some issues with that - possibly in this context. If anyone could shed some light on all this, I would be very thankful.

#include <stdio.h>

struct structItem {
    int age;
    int price;
};

void printItem(const struct structItem &item)
{   
    printf("age: %i, price: %i", item.age, item.price);
}

int main()
{
    struct structItem item;
    item.age = 1;
    item.price = 200;

    printItem(item);

    getchar();

    return 0;
}
like image 990
AudioDroid Avatar asked Feb 22 '23 10:02

AudioDroid


1 Answers

In C, you must pass by pointers so you would define printItem like this:

void printItem(struct structItem *item)
{
    printf("age: %i, price: %i", item->age, item->price);
}

To call it, give it the pointer. E.g.:

printItem(&item);
like image 77
Don Cruickshank Avatar answered Feb 23 '23 23:02

Don Cruickshank