创建、传递、返回结构数组并在 C 中循环遍历 int

标签 c arrays struct

我需要执行一个函数,该函数返回具有可变长度的指定 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/

相关文章:

c - C 中的函数如何返回多个值?

c++ - 读取数据文件并将每一列分配给单独的数组

c++ - 删除动态数组的正确方法是什么?

C 错误 在文件范围内进行了可变修改

c - 结构和警告 C

c - 为什么++variable 在 C 中不被视为左值?

c - 这段代码用什么来确定数组的大小?

c - 交换变量并在 C 中打印出来

java - 在 java 中通过 objectoutputstream 发送字节数组

c - 在结构中添加数组后出现段错误(核心已转储)