Gianlucca
Gianlucca

Reputation: 1354

how to get a dynamic array using struct in c

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?

#define MAX 10000

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

Upvotes: 0

Views: 71

Answers (2)

Raman
Raman

Reputation: 2785

First of all use typedef like this

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

Then in main() you go like this:

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

Upvotes: 1

Mohit Jain
Mohit Jain

Reputation: 30489

#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.

Upvotes: 6

Related Questions