【问题标题】:Assigning values to an array Structure member为数组结构成员赋值
【发布时间】:2021-05-19 22:52:24
【问题描述】:

我创建了一个C结构如下,

struct student{
int regNo;
char *name;
int age;
int marks[5]; 
};

然后我创建了一个学生对象作为 S1 并尝试将值一个一个地分配给结构成员。

struct student s1;
s1.regNo= 2312;
s1.name = "Andrew";
s1.age = 20;
s1.marks[5] = { 90,89,70,58,88};

但是当我给 int 标记数组赋值时,它会给我一个编译错误,

3.c: In function 'main':
3.c:18:16: error: expected expression before '{' token
s1.marks[] = { 90,89,70,58,88};

但是当我尝试分别为每个索引分配值时,

s1.marks[0] = 90;
s1.marks[1] = 89;
s1.marks[2] = 70;
s1.marks[3] = 58;
s1.marks[4] = 88;

问题已解决。

我能否知道我在第一次尝试中做错了什么,我一次性为数组赋值?

【问题讨论】:

    标签: arrays c structure


    【解决方案1】:

    {90,89,70,58,88} 是数组initialiser 的一个示例。仅在声明变量时才有效,例如以下是有效的。

    int array[5] = {90,89,70,58,88};
    

    但这不是:

    int array[5];
    array = {90,89,70,58,88};
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 2015-12-20
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      相关资源
      最近更新 更多