gpt4 book ai didi

c - 为结构体动态分配内存

转载 作者:行者123 更新时间:2023-11-30 21:11:03 24 4
gpt4 key购买 nike

大家好,我有一个问题,我将如何为我的结构项正确分配内存,我收到两个错误:“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*));
}
}

我还在 main 中初始化了:

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/

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