简体   繁体   English

如何在C中使用struct?

[英]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; 我在data.i = a;出错data.i = a; and data.j = b; 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)) ? 另外,我应该在malloc(sizeof(struct Point))之后使用free() malloc(sizeof(struct Point))吗?

data is a pointer. data是一个指针。 You have to say data->i etc. Only call free() when you no longer need the data structure. 您必须说出data->i等。仅在不再需要数据结构时才调用free()

data is a pointer to a struct, not an actual struct. data是指向结构的指针,而不是实际的结构。 You should use data->i instead. 您应该改为使用data->i

And yes, if you malloc() a struct, then you should free() it when you're done with it. 是的,如果您malloc()一个结构,那么完成后就应该free()它。

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. 首先,应该使用star运算符取消引用它,然后可以使用它。 The "->" operator is the abbreviated form of "*v." “->”运算符是“ * v”的缩写形式。 where v is a pointer to a struct. 其中v是指向结构的指针。 So you have data->i which is equivalent to *data.i 所以你有data->i相当于*data.i

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

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