I am new to C, but not to programming. I have been roped into modifying a C program to make it gather multiple pieces of data and put them in an array. I am not allowed to post actual source code, so I have made the following example which illustrates what I am trying to do:
#include <windows.h>
typedef struct
{
int size;
long rpm;
} ENGINE;
typedef struct
{
int doors;
int wheels;
ENGINE engine;
} CAR;
int newCar(CAR *car)
{
ENGINE eng;
eng.rpm=30000;
eng.size=1600;
car->doors=4;
car->wheels=4;
car->engine=eng;
return 0;
}
int getCars(CAR *cars[], int n)
{
int i = 0;
for (i=0; i<n; i++)
{
newCar(cars[i]);
}
return 0;
}
int carCount(int *count)
{
*count = 4;
return 0;
}
int main()
{
int n = 0;
CAR *cars = (CAR*) malloc(sizeof(CAR));
carCount(&n);
cars = (CAR*)realloc(cars, n * sizeof(CAR));
cars[1].doors = 2;
getCars(&cars,n);
}
The code above compiles but fails when I try to set members of the car struct inside the newCar routine. I’m not sure whether my realloc on the cars array is doing what I want it to, I based it on some other posts on stackoverflow. Does it look ok?
How can I access the members of car from the newcar routine?
Is this a reasonable way of doing this?
Many thanks 🙂
You don’t need double indirections!
A simple pointer to CAR can point to different CARs.
Create space for the number of CARs you need: ok
A pointer to the first CAR in that space can easily be made to point to the other CARs.
if malloc didn’t fail
carspoints to a space large enough to hold 1 CARif realloc didn’t fail
carsnow points to a space large enough to holdncarspass that pointer to your functions, along with how many cars it points to
and use the pointer in the functions