-2

When trying to assign a new string value to an existing char array in c, I get the following error:

assignment to expression with array type
  employees[id].FirstMiddleName = NewFirstMiddleName;
                            ^                        

I thought both variables were arrays of the same size so I don't understand what the error is referring to or how to fix it.

struct employee {
    char LastName[30];
    char FirstMiddleName[35];
    float Salary;
    int YearHired;
};

int modify(int id) {
    char NewLastName[30];
    char NewFirstMiddleName[35];
    float NewSalary;
    int NewYearHired;

    printf("Enter new first (and middle) name(s): \n");
    gets(NewFirstMiddleName);
    employees[id].FirstMiddleName = NewFirstMiddleName;

    printf("Enter new last name: \n");
    gets(NewLastName);
    employees[id].LastName = NewLastName;
    ....

}

int main() {

    struct employee *ptr, person;
    ptr = &person;

    ptr->LastName[0] = '\0';
    ptr->FirstMiddleName[0] = '\0';
    ptr->Salary = -1;
    ptr->YearHired = -1;

    for(int i = 0; i < 20; i++) {
            employees[i] = person;
            //printf("%i\n", i);
    }
    ....
}
  • 2
    You cannot copy arrays by assignment in C. You must use `strcpy` (or, better, `strncpy`) to copy a string. [**And you should never use `gets()`**](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) - didn't your compiler tell you? – DYZ Dec 30 '18 at 03:18
  • the function: `gets()` has been depreciated for years and completely removed from the recent version(s) of C. Suggest using `fgets()` (with appropriate parameters – user3629249 Dec 30 '18 at 04:27

1 Answers1

2

employees[id].FirstMiddleName is of array type which cannot be assigned using =

assignment operator shall have a modifiable lvalue as its left operand. A modifiable lvalue is an lvalue that does not have array type

In this case you need to use strcpy

strcpy(employees[id].FirstMiddleName, NewFirstMiddleName);
Auxilus
  • 217
  • 2
  • 9