From:https://stackoverflow.com/questions/18273370/the-correct-way-to-initialize-a-dynamic-pointer-to-a-multidimensional-array

Let's start with some basic examples.

When you say int *P = new int[4];

  1. new int[4]; calls operator new function()
  2. allocates a memory for 4 integers.
  3. returns a reference to this memory.
  4. to bind this reference, you need to have same type of pointer as that of return reference so you do

    int *P = new int[4]; // As you created an array of integer
    // you should assign it to a pointer-to-integer

For a multi-idimensional array, you need to allocate an array of pointers, then fill that array with pointers to arrays, like this:

int **p;
p = new int*[5]; // dynamic `array (size 5) of pointers to int` for (int i = 0; i < 5; ++i) {
p[i] = new int[10];
// each i-th pointer is now pointing to dynamic array (size 10)
// of actual int values
}

Here is what it looks like:

To free the memory

  1. For one dimensional array,

     // need to use the delete[] operator because we used the new[] operator
    delete[] p; //free memory pointed by p;`
  2. For 2d Array,

    // need to use the delete[] operator because we used the new[] operator
    for(int i = 0; i < 5; ++i){
    delete[] p[i];//deletes an inner array of integer;
    } delete[] p; //delete pointer holding array of pointers;

Avoid memory leakage and dangling pointers!

最新文章

  1. 从抽象谈起(三):AOP编程和ASP.NET MVC
  2. solr导入mysql数据库
  3. 抓包工具__Windows
  4. 转:关于视频H264编解码的应用实现
  5. 20150323--MVC
  6. 【PHPsocket编程专题(实战篇③)】构建基于socket的HTTP请求类
  7. 如何配置Spring的XML文件及使用
  8. Python学习笔记——进阶篇【第九周】———线程、进程、协程篇(队列Queue和生产者消费者模型)
  9. 关于iOS自定义控件:在view上实现事件和代理
  10. poptest老李谈分布式与集群 1
  11. 利用CSS3实现鼠标悬停在图片上图片缓慢缩放的两种方法
  12. Anaconda换源小记
  13. CSS粘住固定底部的5种方法
  14. hdu 4407 容斥原理
  15. mysql开发常用小结
  16. Ogre 渲染目标解析与多文本合并渲染
  17. Linux内核分析-分析Linux内核创建一个新进程的过程
  18. 为My97DatePicker日期插件设置默认日期
  19. HADOOP/HDFS Essay
  20. xampp本地服务器+HBuilder配置php环境

热门文章

  1. PHP获取文件大小的方法详解
  2. 2733: [HNOI2012]永无乡
  3. openstack时间不同步问题
  4. python学习之python安装
  5. ajax请求案例
  6. 【Java】 剑指offer(36) 二叉搜索树与双向链表
  7. 015 在Spark中关于groupByKey与reduceByKey的区别
  8. python json数据处理
  9. POJ1006 Biorhythms【中国剩余定理】
  10. Linux学习之常用压缩命令(三)