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

标签 c arrays struct typedef

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

#define MAX 10000

typedef struct Car{
    char model[20];
    char numberCode[20];
    float weight, height, width, length;
}cars[MAX];

最佳答案

#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 */

当你写的时候:

typedef struct Car{
  ...
}cars[MAX];

cars 是一种包含 MAX 汽车的复合类型,这可能不是您想要的。

关于c - 如何在c中使用struct获取动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31108254/

相关文章:

c - 填充结构内存使用

c++ - 指针递增递减语法差异

c - 如何使用堆栈帧访问函数的第一个参数?

CCS/MSP430FR6989 : Capture/Compare Interrupt not working with HR-S04 Ultrasonic Sensor

c++ - 从ppm文件读取RGB值,并使用结构将其存储到称为 “Image”的2d数组中(动态数组)

c++ - 使用内联函数定义静态二维数组

PHP 将数组拆分为两个数组 - 键数组和值数组

c - 如何修复 malloc() 的控制台返回 : memory corruption (fast)

c++ - 在 SWIG 中包装 C++ 结构模板

c - c语言调用函数什么时候加 '&'什么时候不加?