在我的程序中,我创建了一个名为 student
的 struct
,它有两个 int
字段 ID
和 类号
。如果我创建一个包含 20 个学生的二维数组,我该如何使用循环遍历数组并为每个学生分配值?为此,值按数字顺序排列,1-20 和 30-50,所以我认为使用 for 循环应该会很容易,但我无法让它工作。我基本上需要它在完成后返回指向数组的指针。
typedef struct student
{
int ID;
int classNum;
};
//Creates a 4x5 array of students
struct student classroom [4][5];
//Creates the function that will return the array
student **makeClass()
{
int classNumba = 30;
int x = 0;
for(x = 1; x <= 20; x++)
{
classroom[x].ID = x;
classroom[x].classNum = classNumba;
classNumba++;
}
return classroom;
}
最佳答案
你需要有 2 个循环而不是下面的 1 个,
for(i = 0; i <4; i++)
{
for(j = 0; j <5; j++)
{
classroom[i][j].ID = (i+1) * (j+1);
classroom[i][j].classNum = classNumba;
classNumba++;
}
}
此外,由于 classroom
是全局的,因此您无需返回它。
关于c - 如何在 C 中填充二维结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34082252/