简体   繁体   中英

How to use struct in c?

Here is my code:

struct Point
{
    int i;
    int j;
};

int main(int argc, char *argv[])
{
    int n = atoi(argv[1]);
    int a;
    int b;
    for(a = 0; a < n; a++)
    {
        for(b = a+1; b < n; b++)
        {
            struct Point *data = (struct Point *) malloc(sizeof(struct Point));
            data.i = a;
            data.j = b;
            // do something here
            free(data);
        }
    }

    return 0;
}

I got an error at data.i = a; and data.j = b; :

error: request for member 'i' in something not a structure or union
error: request for member 'j' in something not a structure or union

How can I fix this error?

Also, should I use free() after malloc(sizeof(struct Point)) ?

data is a pointer. You have to say data->i etc. Only call free() when you no longer need the data structure.

data is a pointer to a struct, not an actual struct. You should use data->i instead.

And yes, if you malloc() a struct, then you should free() it when you're done with it.

In addition to the answers above, a little explanation:

You have a pointer to a struct. First, you should dereference it, with the star operator, and then you can use it. The "->" operator is the abbreviated form of "*v." where v is a pointer to a struct. So you have data->i which is equivalent to *data.i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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