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

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

最佳答案

employees[id].FirstMiddleName 是数组类型,不能使用 =

赋值

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

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

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

关于c - 将新字符串值分配给 char 数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53975030/

相关文章:

c - 一般竞赛条件

c - 只有标题中的第一个函数有效,但最后两个函数在 c 中不起作用

c - 简单的堆栈程序不接受输入并崩溃

c - 如何以编程方式为接口(interface)获取 linux 接口(interface)别名(IFLA IFALIAS)?

计算完全替代的密码排列

c - GCC 中的段错误

c - 将 unsigned int 递减到 0 未定义行为以下吗?

比较 OpenCV 中的直方图并标准化相似度指数

c - 为什么最大负整数-2147483648的绝对值还是-2147483648?

c - 二进制文件的加密和解密问题