在堆区开辟内存的几种方式

  1. malloc函数

    #include <malloc.h>
    int * p = (int *)malloc(sizeof(int) * 10);
  2. new关键字创建数、数组,仅C++

    int * func() {
     int * p = new int[10]; // 用指针接收new出来的堆区空间
     int * q = new int(10); // 区别于上行,这行只创建一个int型变量
     delete q; // 释放q指向的堆区数据
     return p;
    }
    void test() {
     int * p = func();
     delete [] p; // 释放p指向的堆区数据,注意释放数组的写法里有中括号
    }

标签: none

添加新评论