c - 在函数中使用结构体作为参数

标签 c function structure

如何使用结构体作为函数的参数?我试过这个:

struct
{
    char name[30];
    char section[20];
    float grade;
}student[30];

读取信息并将其存储到结构中后,我调用了将数据写入文件的函数:

show(f,n,student); //n is the number of students

这是显示函数:

void show(FILE *f,int n, struct elev);
{
...
}

谢谢。

最佳答案

你最好命名你的结构:

struct student_st {
  char name[30];
  char section[20];
  float grade;
};

由于您有几个学生,您可能想要传递一个指向他们(数组)的指针:

void show(FILE *f,int n, struct student_st* s) {
  assert (f != NULL);
  assert (s != NULL);
  for (int i=0; i<n; i++) {
    fprintf(f, "name: %s; section: %s; grade: %f\n",
            s->name, s->section, s->grade);
  };
  fflush(f);
}

您将像这样使用它:

#define NBSTUDENTS 30
struct student_st studarr[NBSTUDENTS];
memset (studarr, 0, sizeof(studarr));
read_students (studarr, NBSTUDENTS);
show (stdout, NBSTUDENTS, studarr);

了解 arrays are decaying into pointers .

关于c - 在函数中使用结构体作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21217343/

相关文章:

用静态库编译PIC对象

c - 将变量直接传递给 C 中的函数?

c - 为什么当数据类型是 unsigned int 时会无限循环?

c - 将多维数组写入文本文件

c - Linux 和 Windows 上结构的不同值

c socket prog - select() 问题

c - 在 C 中传递和返回数组

javascript - 检查javascript函数是否存在并执行它

c - 这两个指针有什么区别

MySQL 文本字段和内存使用