c - 如何将嵌套结构体数组作为参数传递给函数?

标签 c arrays function struct

我有 2 个名为 Class 和 Student 的结构。我想通过访问 Class 结构中的 Students[30] 数组来计算学生的平均成绩。

这是我的代码:

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

typedef struct Student{
  char name [20] ;
  int grade ;
  int number ;
} Student;

typedef struct Class{
  char className[20] ;
  Student Students[30] ;
} Class;  

double calculateAverageGrade(/* I want to pass the Students[30] array here */ ) {
  int i ;
  int sum = 0 ;
  for(i=0;i<3;i++) {
  }
  return sum/3 ;
}   

int main() {
  Student s1 ={"John",75,758} ;
  Student s2 = {"Jack",85,123} ;
  Student s3 = {"Lisandra",50,321} ;
  Class c1 ={'\0'} ;

  strcpy(c1.className,"Physics") ;

  c1.Students[0] = s1 ;
  c1.Students[1] = s2 ;
  c1.Students[2] = s3 ;

  calculateAverageGrade(/*needs to take Students[30] array*/);
  return 0 ;
}        

我已经尝试过类似的 Class Students[30]Class.Student Students[30] ,但它们不起作用。

最佳答案

你可以像这样计算平均成绩,就像你的程序一样。请注意,我在函数调用中添加了学生人数,但您的类型 Class 无论如何都应该包含该数量,并且最好将 Class 传递给函数,不仅仅是它包含的数组。

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

typedef struct Student{
    char name [20];
    int grade;
    int number;
}Student;

typedef struct Class{
    char className[20];
    Student Students[30];
}Class;  

double calculateAverageGrade(Student *Students, int count) {  // pass the number of students
    int i;
    int sum = 0;
    for(i = 0; i < count; i++) {                 // don't guess the number of students
        sum += Students[i].grade;
    }
    return (double)sum / count;                  // otherwise integer division
}   

int main(void) {
    Student s1 = { "John",     75, 758 };
    Student s2 = { "Jack",     85, 123 };
    Student s3 = { "Lisandra", 50, 321 };
    Class c1 = {'\0'};
    strcpy(c1.className, "Physics");
    c1.Students[0] = s1;
    c1.Students[1] = s2;
    c1.Students[2] = s3;
    printf("The average grade in %s is %.2f\n", c1.className,
            calculateAverageGrade(c1.Students, 3));
return 0;
}     

程序输出:

The average grade in Physics is 70.00

关于c - 如何将嵌套结构体数组作为参数传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199840/

相关文章:

arrays - 能否在常数时间 O(1) 内使用 n 个 Common CREW 处理器在大小为 n 的排序数组中找到元素 x?

c++ - 如何将成员函数引入作用域?

C 编程从命令行输入字符串中读取整数

python - NumPy 中的 cumsum 函数在添加时会衰减吗?

c - 为什么 C 中的 printf() 方法设计为接受任意数量的参数?

ios - 清除 NSMutableArray 以存储新的 json 它

c++ - 为什么它试图发送一个字符数组而不是一个字符串?

javascript - Dojo/Dijit ById 设置参数

c - 如何确定嵌入式程序正在使用多少堆栈空间

c - 在 C 程序上通过 execve/l 执行 omxplayer 不会在 fork() 之后在子进程的非 X 控制台上输出视频