【问题标题】:Read the grade of students by Array C++ [duplicate]通过Array C++读取学生的成绩[重复]
【发布时间】:2014-12-06 20:36:04
【问题描述】:

这个简单的程序可以读取学生的成绩。我想取用户想输入多少学生,但是当我写int g[size];时会出现编译错误!不知道怎么写正确?

#include <iostream> 
using namespace std;

    int main()
    {
        int x;
        cout << "Enter how many student ..?  ";
        cin >> x;
         const int size = x;
        int g[size];
        cout << "enter " << size << "your ";
        for (int i = 0; i < size; i++){
            cin >> g[i];
        }
        for (int i = 0; i < size; i++){
            cout << "student" << i + 1 << "grade is : " << g[i] << endl;
        }

   system("pause");
    return 0 ;
}

【问题讨论】:

  • "但是当我写 int g[size]; 它不起作用!" 它不起作用到底是什么意思?不会编译?崩溃?没有达到你的预期?具体一点。
  • “它不起作用”是什么意思?有错误吗?如果结果与您想要的不同,以哪种方式?请提供更多详细信息。
  • 崩溃!如果我写 const int size=4 (value) 它会起作用,但我希望用户输入大小
  • 为我工作:ideone.com/JIfpRJ
  • @David 你是怎么做到的?我拿了一份,但出了点问题!

标签: c++


【解决方案1】:

int g[size]; 行导致编译错误,因为 size 在编译时未知(但显然在运行时)。 所以需要在运行时为数组分配内存。

int *g = new int[size]; // instead of int g[size];

这存储了指向 g 中数组第一个元素的指针。现在编译器无法再跟踪数组的生命周期并在不再需要它时为您删除它,因此您也需要自己执行此操作。

delete[] g; // this frees the memory again
system("pause");

附带说明:您的程序是有效的 C++14,微软的 Visual C++ 编译器尚未(完全)支持,但其他编译器如 clang 和 g++ 已经支持它。

【讨论】:

  • 谢谢 :) 我想知道 c++ 11 和 c++14 有什么不同 ...?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-10
  • 1970-01-01
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多