获取结构向量的索引号

时间:2016-12-30 14:58:11

标签: c vector struct

是否有可能获得结构向量的索引? IE我有一个结构学生,成员姓名,人数和年龄。假设我有5名学生,尼尔森编号2160482,路易斯编号2160483,马里奥编号2160484,约翰编号2160485和尼科尔编号2160486。我想获得每个学生的矢量索引,我该怎么办?

typedef struct {
    char name[30];
    int number;
    int age;
} tStudents;

tStudents vStudents[];

void check_data(tStudents vStudents[], int numStudents) {
    int n;

    for (n = 0; n < numStudents; n++) {
        printf("Students registered with the nr. %i:\n", vSoft[n]);//this doesnt work, any idea how to get this value ?
        printf("Name: %s\n", vStudents[n].name);
        printf("Number: %i\n", vStudents[n].number);
        printf("Age: %i\n", vStudents[n].age);
    }
    getchar();
}

1 个答案:

答案 0 :(得分:1)

我不确定你的问题是什么。您可以尝试以下代码,我希望可以帮助您。

#include <stdio.h>
#include <string.h>

#define nr 5

typedef struct {
    char *name;
    int number;
    int age;
} tStudents;

tStudents vStudents[nr];

void check_data(tStudents vStudents[], int numStudents) {
    int n;

    for (n = 0; n < numStudents; n++) {
        printf("Students registered with the nr. %i:\n", n);
        printf("Name: %s\n", vStudents[n].name);
        printf("Number: %i\n", vStudents[n].number);
        printf("Age: %i\n", vStudents[n].age);
    }
    getchar();
}

int main() {

    vStudents[0].name = "Nelson";
    vStudents[0].number = 2160482;
    vStudents[0].age = 12;

    vStudents[1].name = "Louis";
    vStudents[1].number = 2160483;
    vStudents[1].age = 12;

    vStudents[2].name = "Mario";
    vStudents[2].number = 2160484;
    vStudents[2].age = 12;

    vStudents[3].name = "John";
    vStudents[3].number = 2160485;
    vStudents[3].age = 12;

    vStudents[4].name = "Nicole";
    vStudents[4].number = 2160486;
    vStudents[4].age = 12;

    check_data(vStudents, nr);
    return 0;
}

测试

Students registered with the nr. 0:
Name: Nelson
Number: 2160482
Age: 12
Students registered with the nr. 1:
Name: Louis
Number: 2160483
Age: 12
Students registered with the nr. 2:
Name: Mario
Number: 2160484
Age: 12
Students registered with the nr. 3:
Name: John
Number: 2160485
Age: 12
Students registered with the nr. 4:
Name: Nicole
Number: 2160486
Age: 12