【发布时间】:2021-01-27 01:40:06
【问题描述】:
所以我有一个 C++ 练习。我有一个结构学生,它有以下成员:1 个 int、2 个 char、1 个 float 和(我写了练习中的行):“用于读取数据的函数的两个指针 void (read)(student st) 和一个显示数据的指针 void (write)(studentst) "
我必须从键盘读取学生人数,然后为一个有学生的数组分配内存。
然后我必须定义 2 个函数:void readData(student* st) 和 void writeData(student* st),它们读取并显示一个学生结构的成员。我必须遍历学生数组并使用 void readData(student) 初始化指向函数 void (read)(studentst) 和 void (write)(studentst) 的指针* st) 和 void writeData(student* st)。在这里我有点困惑。
我需要做的最后一件事是遍历学生数组并调用函数 v[i].read(&v[i]) 和 v[i].write(&v[i]) 来读取和显示数据。
这是我的代码:
标题
#pragma once
struct student {
int nrID;
char name[100];
char gender[20];
float mark;
void(*read)(student* st);
void(*write)(student* st);
};
void readStudents(int n);
void readData(student* st);
void writeData(student* st);
函数文件
#include <iostream>
#include "header.h"
using namespace std;
void readStudents(int n) {
cout << "Number of students: ";
cin >> n;
student *v;
v = new student[n]; // here I allocate the students array
/*
for(int i=0; i<n; ++i) {
v[i].read(??) = readData(&v[i]);
v[i].write(??) = writeData(&v[i]);
}
*/ // Here I am confused. I'm not sure if I initialized the pointers to function in a right way.
for (int i = 0; i<n; ++i) {
v[i].read(&v[i]);
v[i].write(&v[i]);
}
}
// below I created 2 functions which read and display the members of one student struct.
void readData(student* st) {
cout << "Enter the nrId: ";
cin >> st->nrID;
cout << "Enter the name: ";
cin >> st->name;
cout << "Enter the gender: ";
cin >> st->gender;
cout << "Enter the mark: ";
cin >> st->mark;
}
void writeData(student* st) {
cout << "Id number: " << st->nrID << endl;
cout << "Name: " << st->name << endl;
cout << "Gender: " << st->gender << endl;
cout << "Mark: " << st->mark << endl;
}
主文件
#include <iostream>
#include "header.h"
using namespace std;
int main()
{
int n;
readStudents(n);
return 0;
}
我在代码块中编译代码,我所拥有的只是“学生人数:”程序崩溃。 如何修复那些指针初始化?
【问题讨论】:
标签: c++ function pointers struct