Omar Caceres
Omar Caceres

Reputation: 27

How to solve the error: assignment to expression with array type

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;


};

Upvotes: 3

Views: 19079

Answers (3)

Guillermo Gerard
Guillermo Gerard

Reputation: 892

You are declaring the fixed size arrays in the struct.

Maybe you want to do this:

struct carinfo_t {

char *brand;
char *model;
int year;
float value;
};

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

Two things.

  1. 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).

  2. 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.

Upvotes: 2

mustachioed
mustachioed

Reputation: 533

It seems you may have mistyped the definition of your struct. Maybe change it to something like this:

struct carinfo_t {
    char* brand;
    char* model;
    int year;
    float value;
};

The reason you are getting that error is because you are trying to assign the pointer returned by malloc to an array. That won't work. You should instead be storing the pointer returned by malloc in a char*.

Upvotes: 0

Related Questions