【问题标题】:array type 'char [30]' is not assignable [duplicate]数组类型'char [30]'不可分配[重复]
【发布时间】:2020-11-23 11:47:02
【问题描述】:

我有一些名为“List”的结构,其中包含 id、薪水、工人姓名和指向列表下一个节点的指针。 那里有代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
  int id;
  int salary;
  struct node *next;
  char name[30];
} List;

int main() {
  List *head = (List *) malloc(sizeof(List)); //allocated memory for head
  if(head == NULL) {
    return 1;
  }

  head -> id = 332513075;
  head -> salary = 100;
  head -> name = "Name Lastname";
  // head -> phone = "0532554891";
  // head -> position = "CEO";
  head -> next = NULL;

  print_list(*head);

  return 0;
}

错误信息:array type 'char [30]' is not assignable 这里出了什么问题以及如何解决?

【问题讨论】:

  • 旁白:不要考虑List *head = (List *) malloc(sizeof(List));,而是考虑整洁的List *head = malloc(sizeof *head);

标签: arrays c struct c-strings


【解决方案1】:

数组是不可修改的左值。那就是数组没有赋值运算符。您必须将一个数组中的元素复制到另一个数组中。

所以代替这个声明

head -> name = "Name Lastname";

#include <string.h>

//...

strcpy( head -> name, "Name Lastname" );

【讨论】:

    猜你喜欢
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    相关资源
    最近更新 更多