MST

星途 面试题库

面试题:C语言结构体数组遍历与元素查找

假设有一个结构体数组,结构体定义如下:struct Student { int id; char name[20]; float score; }; 请编写一个函数,在给定的结构体数组中,根据传入的id查找对应的学生信息,并返回该学生的结构体指针。如果未找到,返回NULL。数组大小已知,假设为100。
25.9万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <string.h>

struct Student { 
    int id; 
    char name[20]; 
    float score; 
};

struct Student* findStudentById(struct Student students[], int size, int targetId) {
    for (int i = 0; i < size; i++) {
        if (students[i].id == targetId) {
            return &students[i];
        }
    }
    return NULL;
}

你可以使用如下方式调用这个函数:

int main() {
    struct Student students[100];
    // 假设这里对students数组进行了初始化

    int targetId = 10; // 要查找的id
    struct Student* result = findStudentById(students, 100, targetId);
    if (result != NULL) {
        printf("找到学生: id = %d, name = %s, score = %.2f\n", result->id, result->name, result->score);
    } else {
        printf("未找到对应id的学生\n");
    }
    return 0;
}