如何在c中使用struct获取动态数组

Gia*_*cca 0 c arrays struct typedef

在下面的代码中,我将我的汽车数组设置为最大长度10000,但如果我想将数组大小设置为用户将输入的数字,我该怎么办?

#define MAX 10000

typedef struct Car{
    char model[20];
    char numberCode[20];
    float weight, height, width, length;
}cars[MAX];
Run Code Online (Sandbox Code Playgroud)

Moh*_*ain 6

#include <stdlib.h> /*Header for using malloc and free*/

typedef struct Car{
    char model[20];
    char numberCode[20];
    float weight, height, width, lenght;
} Car_t;
/*^^^^^^ <-- Type name */

Car_t *pCars = malloc(numOfCars * sizeof(Car_t));
/*                       ^            ^         */
/*                      count     size of object*/
if(pCars) {
  /* Use pCars[0], pCars[1] ... pCars[numOfCars - 1] */
  ...
} else {
  /* Memory allocation failed. */
}
...
free(pCars); /* Dont forget to free at last to avoid memory leaks */
Run Code Online (Sandbox Code Playgroud)

当你写:

typedef struct Car{
  ...
}cars[MAX];
Run Code Online (Sandbox Code Playgroud)

汽车是一种包含MAX汽车的复合型汽车,可能这不是你想要的.