简体   繁体   English

指向C ++中的指针动态数组的指针

[英]pointer to pointer dynamic array in C++

I've been having bad luck with dynamic pointers when I want to close it. 我想关闭动态指针时运气不好。 why the application wrote to memory after end of heap buffer? 为什么应用程序在堆缓冲区结束后写入内存? how can I close my array? 如何关闭阵列?

int main()
{
    .
    .   
    int **W;
    W = new int* [n];
    for (int i=1; i <= n; i++)
        W[i] = new int[n];
    .
    .
    .
    ast(n,W);

    for(int i = 1; i <=n ; i++)
    {
        delete W[i];
    }
    delete W;
    getch();
}
void ast (int n,int **W)
{
    int **D;
    D = new int* [n];
    for (int i=0; i < n; i++)
        D[i] = new int[n];

    D=W;
    for (int k=1;k<=n;k++)
        for (int i=1;i<=n;i++)
            for (int j=1;j<=n;j++)
                D[i][j]=min(D[i][j],D[i][k]+D[k][j]);
    .
    .
    for(int i = 1; i <=n ; i++)
    {
        delete D[i];
    }
    delete D;
}

The valid range of indices of an array with N elements is [0, N-1] . 具有N元素的数组的索引的有效范围是[0, N-1] Thus instead of for example this loop 因此,而不是例如这个循环

for (int i=1; i <= n; i++)
         ^^^^ ^^^^^^

you have to write 你必须写

for ( int i = 0; i < n; i++ )

As you used operator new [] you have to use operator delete [] So instead of 使用运算符new [] ,必须使用运算符delete []

for(int i = 1; i <=n ; i++)
{
    delete W[i];
}

and

delete W;

you have to write 你必须写

for ( int i = 0; i < n; i++ )
{
    delete [] W[i];
}

and

delete []W;

Function ast does not make sense because apart from other errors it has a memory leak. 函数ast没有意义,因为除其他错误外,它ast内存泄漏。 At first you allocate memory and assign its address to pointer D and then you overwrite this value of the pointer 首先,您分配内存并将其地址分配给指针D ,然后覆盖该指针的值

void ast (int n,int **W)
{
    int **D;
    D = new int* [n];
    for (int i=0; i < n; i++)
        D[i] = new int[n];

    D=W; // <== ???

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM