从一个结构数组中解析一个结构

时间:2011-03-28 19:23:27

标签: c arrays struct

我是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上的其他一些帖子。它看起来不错吗? 如何从newcar例程访问汽车成员? 这是一种合理的方式吗? 非常感谢:))

5 个答案:

答案 0 :(得分:1)

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

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

指向该空间中第一个CAR的指针可以很容易地指向其他CAR。

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

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

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

答案 1 :(得分:0)

getCars中,您将cars定义为CAR *cars[],即指向CAR的指针数组。

main中,&cars是指向CAR s的数组的指针。

代码恰好编译,因为两者都解析为CAR**

我会用以下方式重写代码:

int newCar(CAR** car)
{
    *car = (CAR*)malloc(sizeof(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 main()
{
    int n = 0;
    CAR** cars = (CAR**) malloc(sizeof(CAR*));
    carCount(&n);

    cars = (CAR**)realloc(cars, n * sizeof(CAR*));
    getCars(cars,n);
    cars[1]->doors = 2;
}

答案 2 :(得分:0)

例如,为了使用malloc,您需要stdlib.h标头。由于您正在将指针从malloc转换为(CAR *),因此编译器假定malloc正在返回一个int而不会生成警告。

答案 3 :(得分:0)

你的代码失败的原因是,在main中,cars是一个简单的标量变量,你调用一个子程序,其地址作为参数。在getCars中,cars是一个指针数组,因此cars[i]在您作为参数传递的地址之前读取。这是错误的,因为地址是单个标量变量的地址,而不是表的地址。

为了正确,你应该使用main的{​​{1}}值调用子程序,这正是你用malloc / realloc创建的表的地址。请注意,在这种情况下,子例程原型将只是

cars

答案 4 :(得分:-1)

您通常会使用malloc(n * sizeof(CAR))realloc函数仅适用于过时的编程。