大家好我有问题, 我将如何为我的struct项正确分配内存, 我得到两个错误:'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;
}
答案 0 :(得分: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;
}