gpt4 book ai didi

c - C中的结构(将值分配给结构数组)

转载 作者:行者123 更新时间:2023-12-05 09:35:28 26 4
gpt4 key购买 nike

我有两个用 C 编写的不同代码。它们都只是尝试将值分配给结构。我正在使用 cs50 库来帮助我以简单的方式获取字符串。

对于第一个代码,当我尝试执行它时出现错误。

第一个代码:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

#define MaxStudents 5

typedef struct
{
string name;
int age;
string gender;
}
student;

student students[MaxStudents];

int main(void)
{
students[0] = {"Kevin Mahendra", 22, "Male"};
students[1] = {"Wasis Sirutama", 22, "Male"};
students[2] = {"Alief Dean", 22, "Male"};
students[3] = {"Adwi Lanang", 21, "Male"};
students[4] = {"Dhimas Kuncahyo", 22, "Male"};

for (int i = 0; i < MaxStudents; i++)
{
printf("%s, %i %s", students[i].name, students[i].age, students[i].gender);
}

}

问题(第一个代码):

sorting.c:19:19: error: expected expression
students[0] = {"Kevin Mahendra", 22, "Male"};
^
sorting.c:20:19: error: expected expression
students[1] = {"Wasis Sirutama", 22, "Male"};
^
sorting.c:21:19: error: expected expression
students[2] = {"Alief Dean", 22, "Male"};
^
sorting.c:22:19: error: expected expression
students[3] = {"Adwi Lanang", 21, "Male"};
^
sorting.c:23:19: error: expected expression
students[4] = {"Dhimas Kuncahyo", 22, "Male"};

但是对于第二个代码,它运行良好,没有任何错误。

第二个代码:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

#define MaxStudents 5

struct student
{
string firstName;
string lastName;
int age;
};

int main(void)
{
struct student kevin = {"Kevin", "Mahendra", 22};

printf("%s %s, %i\n", kevin.firstName, kevin.lastName, kevin.age);
}

那么你们认为我的第一个代码有什么问题?预期的表达方式是什么?

如您所见,我只是尝试将值赋值到结构数组中,就像我在第二个代码中所做的那样(但不是数组)。请帮我。谢谢。

最佳答案

初始化(第二段代码)和赋值(第一段代码)是有区别的

此语法仅在您初始化对象时有效,而不是在您赋值时有效。由于结构在分配时被复制,您可以为此使用复合文字:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

#define MaxStudents 5

typedef struct
{
string name;
int age;
string gender;
}
student;

student students[MaxStudents];

int main(void)
{
students[0] = (student){"Kevin Mahendra", 22, "Male"};
students[1] = (student){"Wasis Sirutama", 22, "Male"};
students[2] = (student){"Alief Dean", 22, "Male"};
students[3] = (student){"Adwi Lanang", 21, "Male"};
students[4] = (student){"Dhimas Kuncahyo", 22, "Male"};

for (int i = 0; i < MaxStudents; i++)
{
printf("%s, %i %s\n", students[i].name, students[i].age, students[i].gender);
}
}

https://godbolt.org/z/KvE7G1

关于c - C中的结构(将值分配给结构数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65846035/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com