Skip to content

Instantly share code, notes, and snippets.

@Unbinilium
Last active October 30, 2019 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Unbinilium/fc305b3e0dc7b0763dbf9efc11b281aa to your computer and use it in GitHub Desktop.
Save Unbinilium/fc305b3e0dc7b0763dbf9efc11b281aa to your computer and use it in GitHub Desktop.
Use undefined array in cpp

In C/C++, we can define multidimensional arrays in simple words as array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). A dynamic 2D array is basically an array of pointers to arrays. So you first need to initialize the array of pointers to pointers and then initialize each 1d array in a loop. Example below using new:

#include <iostream>

int main()
{
    int row = 3, col =3;
    array = (int**) new int* [row];
    for (int i = 0; i < row; i++) array[i] = new int[col];
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            array[i][j] = 0;
            cout << array[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

For another purpose we have a powerful tool named vector in c++, let's see how it works.

#include <iostream> 
#include <vector>

int main() 
{
    int row = 3, col =3;
    vector<vector<int>> array(row , vector<int>(col));
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            array[i][j] = 0;
            cout << array[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

Other examples to create multidimensional array using typedef:

typedef int point;

std::map<std::array<int, 2>, point> twodimearray;
twodimearray[std::array<int, 2>{1, 1}] = 0;

std::map<std::array<int, 3>, point> threedimearray;
threedimearray[std::array<int, 3>{1, 1, 1}] = 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment