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?
4
  • 9
    Make an array of structs. You can't create variable names at runtime. Commented Dec 4, 2016 at 23:04
  • @melpomene Clears a lot up. Thank you. Commented Dec 4, 2016 at 23:06
  • Possible duplicate of How to properly malloc for array of struct in C Commented Mar 28, 2018 at 6:33
  • Make an array of struct if size n, choice is yours to declare it static or dynamic memory allocation. Commented Mar 28, 2018 at 7:06

2 Answers 2

0

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

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

Comments

-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

2 Comments

Don't cast malloc(). And in this case either your cast or your sizeof expression is wrong. (Why use a 2-level structure anyway?)
Better: struct car *cars; ... cars = malloc(num * sizeof *cars); ... cars[i].registration_number = 42;

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.