0

Lets say the struct is defined as :

struct car {
   int registration_number;
}

I want to generate a specific number of struct instances as specified by the user.

Enter number of cars: 20
#generate 20 struct instances

I do not want to make an array inside struct but want a separate instance for every car. I cant understand what the protocol is to automatically generate instances.

car1,car2,car3......,car n

I thought I would run a loop but I cant understand how to declare new instance name everytime :

#some loop
struct car instance_name   #how to replace instance_name with actual names?
noob prog
  • 49
  • 1
  • 5

2 Answers2

0

Make an array of structs. You can't create variable names at runtime. – melpomene

Armali
  • 18,255
  • 14
  • 57
  • 171
-2

If you don't know in advance how many car instances you will need, a handy solution is to use malloc to reserve more memory on the fly.

carArray = (struct car**) malloc(numberOfCars*sizeOf(struct car));

for (int i =0; i < numberOfCars; i++)
    carArray[i] = (struct car*) malloc (sizeof(struct car));

A helpful example article here

A user with a similar question here

Community
  • 1
  • 1
Luminaire
  • 334
  • 6
  • 11
  • 2
    Don't cast `malloc()`. And in this case either your cast or your `sizeof` expression is wrong. (Why use a 2-level structure anyway?) – melpomene Dec 04 '16 at 23:49
  • 5
    Better: `struct car *cars; ... cars = malloc(num * sizeof *cars); ... cars[i].registration_number = 42;` – melpomene Dec 04 '16 at 23:52