我需要执行一个函数,该函数返回具有可变长度的指定 struct
数组。然后我应该遍历返回的数组。
示例结构:
typedef struct student {
int id;
char *name;
int grade;
} Student;
函数原型(prototype)1:
Student *students;
students = findStudentByGrade(int grade);
函数原型(prototype)2:
Student *students;
int retval = findStudentByGrade(&students, int grade);
我对上述方法有点困惑。如何才能正确定义一个struct数组?通话功能?并循环直到结束?有人可以帮帮我吗?
最佳答案
您可以通过这种方式进行操作。此代码正在运行。我在 CodeLite 中测试过。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct student {
int id;
char *name;
} Student;
Student *findStudent(int *asize, const int grade);
int main(void)
{
Student *stds;
int asize = 0;
stds = findStudent(&asize, 5);
int i;
for (i = 0; i < asize; i++) {
printf("ID : %i\n", stds[i].id);
}
return 0;
}
Student *findStudent(int *asize, const int grade)
{
struct student *stds = malloc(sizeof(struct student) * 3);
stds[0].id = 10;
stds[1].id = 20;
stds[2].id = 40;
*asize = 3;
return stds;
}
获取 struc 的数组作为返回语句并传递一个带有参数列表的 int 变量以获取大小并使用 for 循环简单地循环。否则你会发现循环有问题。从创建数组的函数中获取数组大小更容易。
关于创建、传递、返回结构数组并在 C 中循环遍历 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22448817/