0

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];
4
  • 3
    Do you know how to use malloc and free for the primitive types like int? Then you know how to dynamically allocate memory for a structure as well. Commented Jun 29, 2015 at 5:20
  • I'm currently studying how to use them. But they seem complicated to me. Commented Jun 29, 2015 at 5:21
  • Also the typedef keyword is used, so cars is not an object. Commented Jun 29, 2015 at 5:23
  • 1
    This will probably make a type definition of an array instead of creating an array of objects. Commented Jun 29, 2015 at 5:24

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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));
    ...  
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.