一听就懂:动态内存分配,new和delete的用法

/*
    功能:new和delete
    时间:2025年2月12日15:25:51
**/
#include<iostream>
using namespace std;
void showArr(int* arr, int len)
{
    for (int i = 0; i < len; i++)
    {
        cout << arr[i] << " ";

    }
    cout << endl;
}
int main()
{
    //动态内存分配
    /*c语言malloc calloc realloc free 函数*/
    int* p = (int*)calloc(6, sizeof(int));
    showArr(p, 6);
    free(p);
    p = nullptr;
    /*C++: new delete 操作符*/
    int* ptr = new int;//申请一个int
    *ptr = 19;
    cout << *ptr << endl;
    delete ptr;
    cout << "ptr" << ptr << endl;

    ptr = new int[10];//申请一个数组
    //用循环赋值
    for (int i = 0; i < 10; i++)
    {
        *(ptr + i) = i;
    }
    showArr(ptr, 10);
    delete[] ptr;
    cout << "ptr" << ptr << endl;
    ptr = nullptr;
    /*用new分配的,用free释放,c语言和C++的不要混用*/
    int* pnew = new int(56);
    cout << *pnew << endl;
    free(pnew);
    return 0;
}

 

posted @ 2025-02-12 17:23  java帝国  阅读(8)  评论(0)    收藏  举报