I am asked to create a carinfo structure and a createcarinfo() function in order to make a database. But when trying to allocate memory for the arrays of the brand and model of the car, the terminal points out two errors.
For:
newCar->brand =(char*)malloc(sizeof(char)*(strlen(brand) + 1));
newCar->model = (char*)malloc(sizeof(char)*(strlen(model) + 1));
it says that there is an error: assignment to expression with array type and an arrow pointing to the equal sign.
struct carinfo_t {
char brand[40];
char model[40];
int year;
float value;
};
struct carinfo_t *createCarinfo(char *brand, char *model, int year, float value){
struct carinfo_t *newCar;
newCar=(struct carinfo_t*)malloc( sizeof( struct carinfo_t ) );
if (newCar){
newCar->brand =(char*)malloc(sizeof(char)*(strlen(brand) + 1));
newCar->model = (char*)malloc(sizeof(char)*(strlen(model) + 1));
strcpy(newCar->brand, brand);
strcpy(newCar->model, model);
//newCar->brand=brand;
//newCar->model=model;
newCar->year=year;
newCar->value=value;
}
return newCar;
};
Two things.
In your code, brand and model are already of array type, they have memory allocated to them based on their size (char [40]) on declaration. You need not allocate any memory using the allocator function (unlike pointers, on other hand).
You cannot assign to an array type. Array types are not suitable for a LHS argument for an assignment operator.This is what basically throws the error you see, but if you adhere to #1, you'll never reach here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With