首页 > 解决方案 > (C) 结构和函数调用中的函数指针(显示有关学生结构的信息)

问题描述

所以我有一个 C++ 练习。我有一个结构学生,它具有以下成员:1 个 int、2 个字符、1 个浮点数和(我写了练习中的行):“用于读取数据的函数的两个指针 void ( read)(student st) 和一个用于显示的指针数据无效(写)(学生st)“

我必须从键盘读取学生人数,然后为学生数组分配内存。

然后我必须定义 2 个函数: void readData(student* st) 和 void writeData(student* st) 读取和显示一个学生结构的成员。我必须遍历学生数组并使用 void readData(student* st) 和 void writeData(student* st)初始化指向函数 void ( read)(student st) 和 void ( write)(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++functionpointersstruct

解决方案


您的程序具有未定义的行为,因为read和的write成员struct尚未分配给任何有效的东西。

我不清楚为什么read并且write不是static. struct最好让它们成为static成员,为它们分配适当的功能,然后使用它们来读/写struct.

struct student {
    int nrID;
    char name[100];
    char gender[20];
    float mark;

    // make these static members
    static void(*read)(student* st);
    static void(*write)(student* st);
};

确保通过添加来更新 .cpp 文件。

void (*student::read)(student* st) = nullptr;
void (*student::write)(student* st) = nullptr;

更新main

int main()
{
   // Assign functions to read/write 
   student::read = readData;
   student::write = writeData;

   int n;
   readStudents(n);
   return 0;
}


推荐阅读