You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言实现字符串链表遇array type 'char[20]'不可赋值错误如何解决

错误原因分析

触发array type 'char[20]' is not assignable报错的核心原因是:C语言中数组名是指向首元素的地址常量,不支持直接用=运算符对数组整体赋值。你代码中head->data = name.data的写法违反了该语法规则,因此编译报错。

除此之外代码还存在几处影响正常运行的逻辑错误:

  • scanf_s使用%[^\n]格式符读取字符串时,未传入缓冲区长度参数,不符合scanf_s的安全调用要求
  • printf打印字符串时错误使用了%c(单字符打印)格式符,应该用%s打印完整字符串
  • printList函数中注释掉了节点指针后移的代码,运行时会进入死循环
  • 未引入<string.h>头文件,无法使用字符串操作函数
修复后的完整代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TWENTY 20

struct Node {
    char data[TWENTY];
    struct Node* next;
};

struct Node* head = NULL;

void printList(struct Node* n);

int main() {
    struct Node name;

    printf_s("Input Char: ");
    // 传入缓冲区大小TWENTY,符合scanf_s的调用要求
    scanf_s("%[^\n]%*c", name.data, TWENTY);

    head = (struct Node*)malloc(sizeof(struct Node));
    // 用strcpy完成字符串拷贝,代替直接数组赋值,安全场景下可替换为strncpy避免溢出
    strcpy(head->data, name.data);
    head->next = NULL; 

    printList(head);

    // 释放malloc申请的内存,避免内存泄漏
    free(head);
    return 0;
}

void printList(struct Node* n) {
    while (n != NULL) {
        // 用%s打印完整字符串
        printf("%s ", n->data);
        // 节点指针后移,避免死循环
        n = n->next;
    }
}

内容的提问来源于stack exchange,提问作者noob_programmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 21:18:00