-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
  • 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() - didn't your compiler tell you? Commented Dec 30, 2018 at 3: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 Commented Dec 30, 2018 at 4:27

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.