注意:如果想用变量来创建数组的个数,必须用malloc函数来申请地址,最后还要free。
在结构体中存放学生信息,每条信息包括:学号,姓名,成绩,按顺序查找学号为1001的学生的具体信息
#include<stdio.h>
#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct student {
int id;
char name[10];
float score;
};
int search(student stu[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
{
if (stu[i].id == key)
return i;
}
return -1;
}
int main()
{
cout << "一个几个学生" << endl;
int n;
cin >> n;
student* stu; //用变量定义数组时要用malloc
stu = (student*)malloc(sizeof(student)*n);
for (int i = 1; i <= n; i++)
{
cout << "第" << i << "个学生" << endl;
cout<< "输入:学号,姓名,成绩" << endl;
cin >> stu[i].id >> stu[i].name >> stu[i].score;
}
int result;
result = search(stu, n, 1001);
cout << "查询结果是" << endl;
cout << "学号:" << stu[result].id << endl;
cout << "姓名:" << stu[result].name << endl;
cout << "分数:" << stu[result].score<< endl;
free(stu);
return 0;
}