Three dimensional arrays of integers in C++

前端 未结 7 1588
野的像风
野的像风 2020-12-17 00:05

I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using

7条回答
  •  没有蜡笔的小新
    2020-12-17 00:09

    Each pair of square brackets is a dereferencing operation (when applied to a pointer). As an example, the following pairs of lines of code are equivalent:

    x = myArray[4];
    x = *(myArray+4);
    

     

    x = myArray[2][7];
    x = *((*(myArray+2))+7);
    

    To use your suggested syntax you are simply dereferencing the value returned from the first dereference.

    int*** myArray = (some allocation method, keep reading);
    //
    // All in one line:
    int   value = myArray[x][y][z];
    //
    // Separated to multiple steps:
    int** deref1 = myArray[x];
    int*  deref2 = deref1[y];
    int   value = deref2[z];
    

    To go about allocating this array, you simply need to recognise that you don't actually have a three-dimensional array of integers. You have an array of arrays of arrays of integers.

    // Start by allocating an array for array of arrays
    int*** myArray = new int**[X_MAXIMUM];
    
    // Allocate an array for each element of the first array
    for(int x = 0; x < X_MAXIMUM; ++x)
    {
        myArray[x] = new int*[Y_MAXIMUM];
    
        // Allocate an array of integers for each element of this array
        for(int y = 0; y < Y_MAXIMUM; ++y)
        {
            myArray[x][y] = new int[Z_MAXIMUM];
    
            // Specify an initial value (if desired)
            for(int z = 0; z < Z_MAXIMUM; ++z)
            {
                myArray[x][y][z] = -1;
            }
        }
    }
    

    Deallocating this array follows a similar process to allocating it:

    for(int x = 0; x < X_MAXIMUM; ++x)
    {
        for(int y = 0; y < Y_MAXIMUM; ++y)
        {
            delete[] myArray[x][y];
        }
    
        delete[] myArray[x];
    }
    
    delete[] myArray;
    

提交回复
热议问题