19.new和delete用于数组

程序1:

//2022年9月20日22:06:27
#include <iostream>
#pragma warning(disable:4996)
using namespace std;

//1.new创建基础类型的数组
void test01()
{
    //申请基础数据类型的数组
    int * pInt = new int [10] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};//不推荐
    for (int i = 0; i < 10; i++)
    {
        pInt[i] = i + 1;
    }

    for (int i = 0; i < 10; i++)
    {
        cout << pInt[i] << " ";
    }
    cout << endl;

    char * pChar = new char[64];
    memset(pChar, 0, 64);
    strcpy(pChar, "小花");
    cout << pChar << endl;

    //注意:如果new时有中括号,那么delete时也要有中括号
    delete [] pInt;
    delete [] pChar;
}
int main()
{
    test01();
    system("pause");
    return EXIT_SUCCESS;
}

输出结果:

1 2 3 4 5 6 7 8 9 10
小花
请按任意键继续. . .
posted @ 2022-09-21 19:18  CodeMagicianT  阅读(27)  评论(0)    收藏  举报