To start, none of the existing solutions I have looked through have the parameter as an array, such as:
void inputCars(Car * cars[], int size);
Here is the code I currently have.
/******************************************************************************
WE WANT:
dynamic array of pointers to a
car structure
*******************************************************************************/
#include <string.h>
#include <stdio.h>
typedef struct {
char make[60];
double price;
int year;
}Car;
int size;
void inputCars(Car* cars[], int size);
int main(int argc , char** args)
{
printf("Enter how many Cars you wish to take inventory of: ");
scanf("%d", &size);
Car cars[size];
inputCars(&(cars), size);
}
void inputCars(Car * cars[], int size)
{
for(int i = 0; i < size; i++)
{
// TODO
}
}
When I try to put the cars array through I get the following error :
expected 'struct Car**' but argument is of type 'struct Car(*)[(sizetype)(size)]'
I understand what Car * cars[] is asking, thanks for the help with that, but I am confused on how I can pass this through.
I am not allowed to change the way the parameters are in the function and am utterly confused as to how to pass the array through.
In this statement
Car cars[size];
there is declared a variable length array.
In this call
inputCars(&(cars), size);
the expression &cars
has the type Car( * )[size]
. But the corresponding function parameter
void inputCars(Car* cars[], int size);
is declared like Car * cars[]
that is adjusted by the compiler to the type Car **
and there is no implicit conversion from one pointer type to another. So the compiler issues an error message.
In the comment to your program there is written
WE WANT:
dynamic array of pointers to a
car structure
So instead of declaring a variable length array you need to allocate dynamically an array of pointers to objects of the type Car
. Something like
Car **cars = malloc( size * sizeof( Car * ) );
for ( int i = 0; i < size; i++ )
{
cars[i] = malloc( sizeof( Car ) );
}
In this case the function can be called like
inputCars( cars, size );