C++初学者动态内存分配

img

img


这个上面是要求,下面是我写的,但一直不对,我刚接触C++,其中有好多低级问题,麻烦看一下,给个正确的,方法,过程

注意 人家都说了动态内存,动态内存应该是需要自己手动申请的内存!!!
简单demo,细节自己优化~

#include <iostream>
using namespace std;

int main()
{
    //总人数由用户输入  动态内存控制
    int num = 0;
    int* score = NULL; //动态内存啊

    cout << "input num:"<< endl;
    cin >> num;
    //申请内存
    score = new(std::nothrow) int[num];
    if (score == NULL) return -1;
    cout << "please input score : \n";
    for (int i = 0; i < num; i++)
    {
        cin >> *(score + i);
    }

    //然后根据输入的号码 取动态内存数组中的值
    int number = 0;
    cout << "inpit find:";
    cin >> number;
    if (number > num || number < 1)
    {
        cout << "ERROR"<<endl;
    }
    else
    {
        cout << *(score + number - 1);
    }

    if (score != NULL)
    {
        delete []score;
        score = NULL;
    }
    return 0;
}