zoukankan      html  css  js  c++  java
  • The correct way to initialize a dynamic pointer to a multidimensional array

    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!

  • 相关阅读:
    从PDF中提取信息----PDFMiner
    python爬取返利网中值得买中的数据
    使用Beautifulsoup爬取药智网数据
    Scrapy--1安装和运行
    BeautifulSoup学习笔记
    windows下安装beautifulsoup4
    C# Json处理相关
    一个Monkey测试的小坑
    Jmeter笔记(Ⅲ) Jmeter的非GUI操作
    Jmeter笔记(Ⅱ)使用Jmeter实现轻量级的接口自动化测试
  • 原文地址:https://www.cnblogs.com/time-is-life/p/9109488.html
Copyright © 2011-2022 走看看