如何在c语言中使用结构体

How to use struct in c?

本文关键字:结构体 语言      更新时间:2023-10-16

下面是我的代码:

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

我在data.i = a;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

如何修复这个错误?

另外,我应该在malloc(sizeof(struct Point))之后使用free()吗?

data是一个指针。你必须说data->i等等。

仅在不再需要该数据结构时调用free()

data是一个指向结构体的指针,而不是一个实际的结构体。您应该使用data->i

是的,如果你malloc()一个结构体,那么你应该free()当你完成它。

除了上面的答案,还有一点解释:

你有一个指向结构体的指针。首先,您应该使用星号操作符对它解引用,然后才能使用它。"->"操作符是"*v"的缩写形式,其中v是指向结构体的指针。这里是data->i相当于*data.i