Eng.Fouad
Eng.Fouad

Reputation: 117587

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))?

Upvotes: 1

Views: 214

Answers (3)

km_1
km_1

Reputation: 26

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

Upvotes: 0

Dan
Dan

Reputation: 10786

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.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477010

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

Upvotes: 4

Related Questions