如何使用双指针动态分配内存 [英] How Can I Allocate Memory Dynamically Using Double Pointer

查看:139
本文介绍了如何使用双指针动态分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<< iostream>>



使用命名空间std;





int main()

{



int ** p;

p = new int [10];



删除[] p;

返回0;

}





这是使用双指针动态分配内存的正确方法。



请解释。

#include <<iostream>>

using namespace std;


int main()
{

int **p;
p=new int[10];

delete[] p;
return 0;
}


Is that right way to allocate memory dynamically using double pointer.

Please explain.

推荐答案

没有。你不需要一个指针指向一个整数,因为你只是分配一个整数数组:一个指向整数的指针 - 大多数现代编译器都会给你尝试时出错,因为你无法将int *转换为int **。



如果你想按原样使用代码,然后从p的声明中删除一个'*'。

否则,你必须在你的编码中变得比较复杂:



No. You don't need a "pointer-to-a-pointer-to-an-integer", because you are only allocating an array of integers: a "pointer-to-an-integer" - and most modern compilers will give you an error when you try, because you cannot convert an "int*" to an "int**".

If you want to use the code as it is, then remove one '*' from the declaration of "p".
Otherwise, you have to be moire sophisticated in your coding:

int main()
    {
    int **p, i;
    p=new int*[10];
    for(i = 0; i < 10; i++)
        {
        p[i] = new int[5];
        }

    ...

    for(i = 0; i < 10; i++)
        {
        delete[] p[i];
        }
    delete[] p;
    return 0;
    }


这篇关于如何使用双指针动态分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆