简体   繁体   中英

How can I allocate memory for triple pointer using a function?

I would like to allocate memory to store/manipulate data using a triple pointer. Given that I have to allocate the data at multiple points in my code, I implemented a function to do it. In the code below I give the implementation of this function and a simple main method that illustrates how I use this function in my code.

The code compile without error but when I run the program it crushes. I would appreciate your help to fix this problem.

EDIT: it crushes in the function AllocateMemory at the line *data[i][j] = new double[x]; for i = 0 and j =1

Thank you.

int main()
{
    int x = 2;
    int y = 2;
    int z = 2;
    double*** data;//
    AllocateMemory(&data, x, y, z);
    //play with data

    FreeMemory(data, x, y, z);
    return 0;
}



void AllocateMemory(double**** data, int x, int y, int z)
{
    *data = new double**[z];

    for(int i = 0; i < z; i++)
    {
        *data[i] = new double*[y];
        for(int j = 0; j < y; j++)
        {
            *data[i][j] = new double[x];
        }

    }
}


void FreeMemory(double*** data, int x, int y, int z)
{
    for(int i = 0; i < z; i++)
    {
        for(int j = 0; j < y; j++)
        {
            delete [] data[i][j];
            data[i][j] = NULL;
        }
        delete [] data[i];
        data[i] = NULL;
    }

    delete [] data;
    data = NULL;
}

Remember that array subscription has a higher precedence than dereference operator. Here:

*data[i] = new double*[y];

You're subscripting data and then dereferencing that pointer. data argument of AllocateMemory is not a pointer to an array, but instead to a single variable which is data in main . Therefore data[1] was never initialized and you get undefined behaviour. Given the context, you probably intended it the other way round:

(*data)[i] = new double*[y];

You have the same bug on the line *data[i][j] = new double[x]; .

You could have avoided this either by using a reference parameter or - as I would recommend - by returning the pointer to the newly allocated array of pointers instead of passing it as an argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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