提问者:小点点

C++指针(学生*[n]给出数组类型不可赋值的错误)


#include <iostream>
#include "student.h"

using namespace std;

int main()
{
    // inputting the number of students
    int n;
    cout << "How many students would you like to process?" << endl;
    cin >> n;
    student* s[n];
    string tmp;
    double t;
    // entering each student details
    for (int i = 0; i < n; i++)
    {
        // dynamically allocating object
        s[i] = new student();
        cout << "Enter first name for student " << (i + 1) << endl;
        cin >> tmp;
        s[i]->setFirstName(tmp);
        cout << "Enter middle name for student " << (i + 1) << endl;
        cin >> tmp;
        s[i]->setMiddleName(tmp);
        cout << "Enter last name for student " << (i + 1) << endl;
        cin >> tmp;
        s[i]->setLastName(tmp);
        cout << "Enter GPA for student " << (i + 1) << endl;
        cin >> t;
        s[i]->setGPA(t);
    }
    double avgGPA = 0;
    // printing the student details
    cout << "Students:" << endl;
    cout << "---------" << endl
        << endl;
    for (int i = 0; i < n; i++)
    {
        cout << s[i]->getFirstName() << " " << s[i]->getMiddleName() << " " << s[i]->getLastName() << " " << s[i]->getGPA() << endl;
        avgGPA += s[i]->getGPA();
    }
    avgGPA /= n;
    // printing the average GPA
    cout << endl
        << "Average GPA: " << avgGPA;
    // freeing the memory allocated to objects
    for (int i = 0; i < n; i++)
        delete s[i];
    return 0;
}

在main函数student*s[n]下;表示数组类型不能赋值给行。它还会给出表达式必须包含文字的错误。我以为我做的每件事都对,但出了个差错。这个错误的解决方案是什么,有人能帮忙吗?


共1个答案

匿名用户

student*s[n];是一个可变长度数组(VLA),标准C++中不包含该数组。

您应该像使用std::vector一样使用std::vectors(n);

还要在代码的开头添加#include来使用它。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|指针|学生|n|给出|数组|类型|赋值)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?