Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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;


};
like image 966
Omar Caceres Avatar asked May 01 '26 04:05

Omar Caceres


1 Answers

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.

like image 108
Sourav Ghosh Avatar answered May 02 '26 22:05

Sourav Ghosh