【问题标题】:C, Expression must be a modifiable lvalue (changing the value of a struct's member) [duplicate]C,表达式必须是可修改的左值(更改结构成员的值)[重复]
【发布时间】:2018-04-19 12:15:21
【问题描述】:

我是一个极端的新手,我只是想学习.. 这是我创建的简单结构

struct Student{
char FirstName[20];
char LastName[20];
char StudentID[10];
char Password[20];}

然后我正在创建一个指针数组;

struct Student *StudentList[10];

然后我调用我的“注册”函数并将数组中的第一个元素作为参数传递,原因是为了将值更改为数组中的特定结构元素,例如我想更改学生的详细信息;

Register(&StudentList[0]);

接下来,我的功能;

void Register(struct Student *student);
void Register(struct Student *student) {student->FirstName = "John";}

这是一个非常简化的示例,很抱歉无法在此处正确粘贴代码。

但是当我尝试分配一个值时,为什么我得到一个“表达式必须是一个可修改的左值”。

【问题讨论】:

    标签: c pointers struct


    【解决方案1】:

    您不能像在 C 中那样分配数组类型,而 "John"char[5] 类型的数组。

    strcpy(student->FirstName, "John");
    

    会这样做,或者更好的是,某种形式的东西

    strncpy(student->FirstName, "John", 20);
    

    这样您就可以避免超出char 缓冲区。

    【讨论】:

      【解决方案2】:

      firstName 字段是一个数组,数组不能作为一个整体赋值。这就是错误消息告诉您的内容。

      由于您要将字符串复制到此数组中,因此应使用 strcpy:

      strcpy(student->FirstName, "John");
      

      【讨论】:

        【解决方案3】:

        在 C 中,不使用 = 设置字符串(也不使用 == 比较它们)。

        你必须使用strcpy函数:

        strcpy( student->firstName, "John" );
        

        【讨论】:

          【解决方案4】:

          首先你忘记在结构声明struct Student { };末尾添加分号

          其次,您传递的是&StudentList[0],而不是只传递StudentList[0] 并首先为此动态分配内存。

          最后,student->FirstName = "John"; 因为student->FirstName 是一个字符缓冲区,而"John" 也是一个缓冲区所以你不能在A = B 那里AB 都是char buffer,而是使用@987654331 @

          这里是示例

          struct Student{
                  char FirstName[20];
                  char LastName[20];
                  char StudentID[10];
                  char Password[20];
          }; /* you forget to put semicolon */
          void Register(struct Student *student)  {
                  strcpy(student->FirstName,"John"); /* use strcpy() */
                  printf("%s\n",student->FirstName);
          }
          int main() {
                  struct Student *StudentList[10];
                  for(int index = 0;index < 10;index++) {
                  StudentList[index] = malloc(sizeof(struct Student)); /* allocate memory for each Student */
                  }
                  Register(StudentList[0]);
          
                  /* free the dynamically allocated memory */
          
                  return 0;
          }
          

          【讨论】:

            猜你喜欢
            • 2017-05-15
            • 2021-09-17
            • 2014-12-15
            • 2014-12-20
            • 2015-09-19
            • 2016-05-09
            • 2016-09-13
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多