Automatically generate struct instances

倖福魔咒の 提交于 2019-12-25 04:26:10

问题


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



来源:https://stackoverflow.com/questions/40964773/automatically-generate-struct-instances

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!