接收错误C4700,无法完成驱动程序

Receiving error C4700 and unable to finish driver program

本文关键字:驱动程序 错误 C4700      更新时间:2023-10-16
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <cctype>
using namespace std;
struct Student {
    char*      name;
    float      gpa;
};
Student * createStudent( char name[], float gpa) {
    Student * studentPtr;
    studentPtr = new Student;
    studentPtr->name = new char[strlen(name) + 1];
    studentPtr->name = name;
    studentPtr->gpa = gpa;
    // Return the pointer
    return studentPtr;
}
bool destroyStudent(Student*& aStudent) {
    if (aStudent) { //check whether this pointer is already null.
        free(aStudent->name);
        delete aStudent; 
        aStudent = nullptr;
        return true;
    }
    return false; //aStudent is already null
}

int main() {
    Student * student1 = createStudent(student1->name, student1->gpa); //error is here
    cout << "Enter Student's name: " << endl;
    cin >> student1->name;
    cout << "Enter GPA: " << endl;
    cin >> student1->gpa;
    cout << student1->name << " and " << student1->gpa << endl;
    destroyStudent(student1);
    if (student1) {
        cout << "Pointer is NOT null!!!" << endl;
        student1 = nullptr;
    }
    if (!student1) {
        cout << "The pointer is null now." << endl;
    }
    return 0;
}

我正试图完成一个驱动程序,在那里我可以测试我的功能,但我一直没有成功。对于我所做的每一个更改,它只会添加更多的错误消息。这是我能得到的最接近的错误,只有一个我无法解决的错误。

错误信息:

错误1:使用未初始化的本地变量"student1"

非常感谢任何帮助。我已经在这里搜索了这个错误,无法解决自己:(

你到底想干什么:

Student * student1 = createStudent(student1->name, student1->gpa);

这是完全错误的!你试图用你试图创建的对象的字段创建一个Student对象——你没有看到这里的逻辑错误吗?

正确的用法之一是:

Student * student1 = createStudent("Smith", 4.0f);

不能使用尚未创建的对象,这样做会导致错误。