Automatically generate struct instances

2019-09-13 08:50发布

问题:

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?

回答1:

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



回答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



标签: c struct