将新的字符串值分配给char数组时出错

时间:2018-12-30 03:16:43

标签: c

当尝试向c中的现有char数组分配新的字符串值时,出现以下错误:

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

我以为两个变量都是相同大小的数组,所以我不明白错误指的是什么或如何解决。

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);
    }
    ....
}

1 个答案:

答案 0 :(得分:2)

employees[id].FirstMiddleName属于数组类型,无法使用=

分配
  

赋值运算符的左值应为可修改的左值。可修改的左值是没有数组类型的左值

在这种情况下,您需要使用strcpy

strcpy(employees[id].FirstMiddleName, NewFirstMiddleName);