首页 > 解决方案 > ['{'标记之前的错误预期表达式

问题描述

您好,我是 C 的初学者,我不知道为什么每次尝试编译时都会在此行出现此错误

    CURRENT->name = {'L','O','U','D','A'};

这是我的整个代码

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

struct node{
char name[15];
int age;
struct node *next;
}TEMPLATE;


int main()
{
    struct node *HEAD;      
    HEAD = (struct node*) malloc (sizeof(struct node)); 
    
    
    struct node *TAIL;
    TAIL = (struct node*) malloc (sizeof(struct node));
 
    
    struct node *CURRENT;
    CURRENT = (struct node*) malloc (sizeof(struct node));
    CURRENT->name = {'L','O','U','D','A'};
    CURRENT->age = 24;
    CURRENT->next = NULL;
    return 0;
}

标签: cstructinitializationc-stringsassignment-operator

解决方案


您只能将花括号列表用作声明的初始值设定项。

但是这个

CURRENT->name = {'L','O','U','D','A'}; 

不是声明而是表达式语句

你可以写

#include <string.h>

//...

strcpy( CURRENT->name, "LOUDA" ); 

注意全局变量 TEMPLATE 的声明

struct node{
char name[15];
int age;
struct node *next;
}TEMPLATE;

没有意义。所以声明结构

struct node{
char name[15];
int age;
struct node *next;
};

并在此语句中动态分配节点

 HEAD = (struct node*) malloc (sizeof(struct node))

推荐阅读