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

时间:2022-12-15 19:56:12

In the code below I have my cars array set to max length of 10000, but what should I do if I want to set the array size to a number that the user will input?

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

#define MAX 10000

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

2 个解决方案

#1


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

When you write:

当你写:

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

cars is a type which is a composite type containing MAX cars and possibly this is not something you want.

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

#2


1  

First of all use typedef like this

首先使用这样的typedef

typedef struct Car
{
   char model[20];
   char numberCode[20];
   float weight, height, width, lenght;
}car_type;

Then in main() you go like this:

然后在main()中你会这样:

 main()
 {
    ...
   int n;
   scanf("%d",&n);
   car_type *cars =(car_type *) malloc(n*sizeof(car_type));
    ...  
 }

#1


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

When you write:

当你写:

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

cars is a type which is a composite type containing MAX cars and possibly this is not something you want.

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

#2


1  

First of all use typedef like this

首先使用这样的typedef

typedef struct Car
{
   char model[20];
   char numberCode[20];
   float weight, height, width, lenght;
}car_type;

Then in main() you go like this:

然后在main()中你会这样:

 main()
 {
    ...
   int n;
   scanf("%d",&n);
   car_type *cars =(car_type *) malloc(n*sizeof(car_type));
    ...  
 }