当前位置: 首页 > 知识库问答 >
问题:

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

虞祯
2023-03-14
#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个答案

谢宸
2023-03-14

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

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

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

 类似资料:
  • 我是angular的新手,我在学习这个hero教程时,偶然发现了这个错误: 我在这里复制了错误。

  • 在我新创建的Angular应用程序中,我尝试使用mattlewis92的Angular日历来创建他的日历。我已经复制了他的github:https://mattlewis92.github.io/Angulat-calendar/#/kitchenter-sink上列出的所有步骤和代码,但我在第一行总是发现一个错误,即指出“{static:boolean;}类型的参数不能分配给{read?:any

  • 我试图约束泛型函数的返回类型。(为了简化示例,请忽略函数的实际“有用性”)。 但是返回语句会导致打字错误- -这让我很困惑。在我的理解中,

  • C++ 指针 在我们讲解指针数组的概念之前,先让我们来看一个实例,它用到了一个由 3 个整数组成的数组:#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; for (int i = 0; i < MAX; i++) { cout << "Va

  • C++ 数组 您可以先跳过本章,等了解了 C++ 指针的概念之后,再来学习本章的内容。 如果您对 C++ 指针的概念有所了解,那么就可以开始本章的学习。数组名是一个指向数组中第一个元素的常量指针。因此,在下面的声明中: double balance[50]; balance 是一个指向 &balance[0] 的指针,即数组 balance 的第一个元素的地址。因此,下面的程序片段把 p 赋值

  • C++ 指针 指针和数组是密切相关的。事实上,指针和数组在很多情况下是可以互换的。例如,一个指向数组开头的指针,可以通过使用指针的算术运算或数组索引来访问数组。请看下面的程序:#include <iostream> using namespace std; const int MAX = 3; int main () { int var[MAX] = {10, 100, 200}; int *pt