【问题标题】:using a structura as a parameter in a function在函数中使用结构作为参数
【发布时间】:2014-01-19 13:26:19
【问题描述】:

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

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);
{
...
}

谢谢。

【问题讨论】:

标签: c function structure


【解决方案1】:

你最好命名你的结构:

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多