c - 如何在 C 中填充二维结构数组?

标签 c arrays struct

在我的程序中,我创建了一个名为 studentstruct,它有两个 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/

相关文章:

python - 如何将字典打包到结构中,以便我可以将其存储在文件中并稍后解压

c - C 结构体中的位域表达式

C : array of struct (which holds an int and another array of another struct)

c - strstr() 不适用于 C

c - 为什么返回一个未初始化的值被认为是未定义的行为?

java - 复制数组并使用 printall() 方法将其大小加 1 以返回新数组中的所有 int

c - 将 C 数组传递给函数

c - 如何计算带位域的结构体的大小?

c - MIPS - 帮助从 C 转换代码

java - 从字符串数组+颜色词中获取每个单词