博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
The correct way to initialize a dynamic pointer to a multidimensional array
阅读量:6432 次
发布时间:2019-06-23

本文共 1370 字,大约阅读时间需要 4 分钟。

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[] operatordelete[] p; //free memory pointed by p;`
  2. For 2d Array,

    // need to use the delete[] operator because we used the new[] operatorfor(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!

 

转载于:https://www.cnblogs.com/time-is-life/p/9109488.html

你可能感兴趣的文章
借力AI 极验如何构建下一代业务安全?
查看>>
用Python制作迷宫GIF
查看>>
支付宝推出基于区块链跨境支付,巨头入场小企业将面临灭顶之灾
查看>>
从事互联网行业,怎样才能快速掌握一门编程语言呢?
查看>>
深入浅出换肤相关技术以及如何实现
查看>>
Redis 基础、高级特性与性能调优
查看>>
React native 第三方组件 React native swiper
查看>>
接口幂等设计
查看>>
编程入门指南
查看>>
移动端的自适应方案—REM
查看>>
你真的懂volatile吗
查看>>
Android 编译时注解-提升
查看>>
说说 Spring AOP 中 @Aspect 的高级用法
查看>>
Workbox CLI中文版
查看>>
贝聊亿级数据库分库分表实践
查看>>
同时连接gitlab和github
查看>>
vuex源码分析
查看>>
tornado+datatables分页
查看>>
集成 Kubernetes 与 Cloud Foundry,IBM自有一套
查看>>
php 中英文字符分割
查看>>