Pin-Jiun / Programming-Language-CPP

It's the note/experience about C++, and I have the basic ability of C.
0 stars 0 forks source link

0.3-Pointer and Array #33

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

Dynamic Array

所謂的動態跟靜態的差別在於, 可否釋放掉記憶體

int n;
cin>>n;
int scores[n];

此時宣告的scores陣列, 並不能主動的釋放掉, 故為靜態的

假設今天有20個班級的學生, 此時陣列不能刪除, 會浪費大量的記憶體空間 此時就可以使用Dynamic Array

動態陣列的建立以及釋放

int * scores = new int[n];
...
delete scores;

new int[n] 會new出一個新的int[n]記憶體空間, 此時第一個記憶體的位置會傳給scores 指標


Dynamic Array實際應用


#include <iostream>

using namespace std;

int main()
{
    int class_count;
    cout<<"請輸入班級數量:";
    cin>>class_count;

    int * ave = new int[class_count];

    for(int i = 0; i<class_count; i++){
        int student_num;
        cout<<"請輸入學生人數:";
        cin>>student_num;

        int * scores = new int[student_num];
        for(int j = 0; j<student_num; j++){
            cout<<"請輸入學生成績:";
            cin>>scores[j];
        }

        double total = 0;
        for(int k =0; k<class_count; k++){
            total += scores[k];
        }

        ave[i] = total/student_num;
        delete scores;
        }
}