嗨,我有一个问题,
我该如何为结构项正确分配内存,
我遇到两个错误:将'sizeof'无效地应用于不完整的类型'struct Car'
和未声明“ numberCar”(此功能首次使用)。似乎无法在这里找到问题的根源...

typedef struct {
    int numberCar;
    int carStatus;
    int** droveCar;
    int currentCar[2];
} Car;

int init(struct Car *cars, int argc, char** argv ) {
    int i, j;

    cars = malloc (3 * sizeof(struct Car));

    for (i = 0 ; i < numberCar ; i++) {
        droveCar[i]=malloc(10 * sizeof(int));
    }

    for (j = 0; j < numberCar; i++) {
        cars[i].droveCar = (int**) malloc(numberCar * sizeof(int*));
    }
}


我在主要方面也有一些启迪之处:

int main() {
    struct Car *cars;

    /......./

    return 0;
}

最佳答案

大概是这样的

#include <stdlib.h>

typedef struct Car {
    int numberCar;
    int carStatus;
    int** droveCar;
    int currentCar[2];
} Car;

void init(Car *car, int numberCar) {
    int i;

    car->numberCar = numberCar;
    //car->carStatus = 0;
    //car->currentCar[0] = car->currentCar[1] = -1;

    car->droveCar = malloc(numberCar * sizeof(int*));
    for (i = 0 ; i < numberCar ; i++) {
        car->droveCar[i] = calloc(10, sizeof(int));
    }
}

int main() {
    struct Car *cars;
    int i;

    cars = calloc(3, sizeof(Car));//struct Car cars[3];// 3 Cars
    for(i = 0; i < 3; ++i)
        init(&cars[i], 3);

    //deallocate
    return 0;
}

关于c - 动态为结构项分配内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26110869/

10-11 21:23