gpt4 book ai didi

c - 解析一个结构体以从结构体数组中运行

转载 作者:行者123 更新时间:2023-11-30 18:06:31 25 4
gpt4 key购买 nike

我是 C 语言新手,但不是编程新手。我被要求修改一个 C 程序,使其收集多条数据并将它们放入一个数组中。我不允许发布实际的源代码,因此我制作了以下示例来说明我正在尝试做的事情:

#include <windows.h>

typedef struct
{
int size;
long rpm;
} ENGINE;


typedef struct
{
int doors;
int wheels;
ENGINE engine;
} CAR;

int newCar(CAR *car)
{
ENGINE eng;
eng.rpm=30000;
eng.size=1600;
car->doors=4;
car->wheels=4;
car->engine=eng;
return 0;

}


int getCars(CAR *cars[], int n)
{
int i = 0;
for (i=0; i<n; i++)
{
newCar(cars[i]);
}

return 0;
}

int carCount(int *count)
{
*count = 4;
return 0;
}

int main()
{
int n = 0;
CAR *cars = (CAR*) malloc(sizeof(CAR));
carCount(&n);

cars = (CAR*)realloc(cars, n * sizeof(CAR));
cars[1].doors = 2;
getCars(&cars,n);

}

上面的代码可以编译,但当我尝试在 newCar 例程中设置 car 结构的成员时失败。我不确定汽车数组上的 realloc 是否正在执行我想要的操作,我基于 stackoverflow 上的其他一些帖子。看起来还好吗?如何从新车例程中访问汽车成员?这是这样做的合理方式吗?非常感谢:)

最佳答案

您不需要双重间接!一个简单的 CAR 指针可以指向不同的 CAR。

为您需要的 CAR 数量创建空间:好的

可以轻松地将指向该空间中第一个 CAR 的指针指向其他 CAR。

    CAR *cars = malloc(sizeof(CAR));

如果 malloc 没有失败 cars 指向一个足以容纳 1 辆车的空间

    cars = realloc(cars, n * sizeof(CAR));

如果 realloc 没有失败 cars 现在指向一个足以容纳 n 辆汽车的空间
将该指针传递给您的函数,以及它指向的汽车数量

    getCars(cars, n);

并在函数中使用指针

int getCars(CAR *cars, int n)
{
int i = 0;
for (i=0; i<n; i++)
{
/* here, cars[0] is the first car; cars[1] is the second ... */
/* we can pass the address with &cars[i] */
/* or make arithmetic with the pointer itself: */
newCar(cars+i);
}
return 0;
}

关于c - 解析一个结构体以从结构体数组中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5463954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com