Pointer-to-pointer dynamic two-dimensional array

后端 未结 5 1792
庸人自扰
庸人自扰 2020-11-28 03:56

First timer on this website, so here goes..

I\'m a newbie to C++ and I\'m currently working through the book \"Data structures using C++ 2nd ed, of D.S. Malik\".

5条回答
  •  粉色の甜心
    2020-11-28 04:17

    This code works well with very few requirements on external libraries and shows a basic use of int **array.

    This answer shows that each array is dynamically sized, as well as how to assign a dynamically sized leaf array into the dynamically sized branch array.

    This program takes arguments from STDIN in the following format:

    2 2   
    3 1 5 4
    5 1 2 8 9 3
    0 1
    1 3
    

    Code for program below...

    #include 
    
    int main()
    {
        int **array_of_arrays;
    
        int num_arrays, num_queries;
        num_arrays = num_queries = 0;
        std::cin >> num_arrays >> num_queries;
        //std::cout << num_arrays << " " << num_queries;
    
        //Process the Arrays
        array_of_arrays = new int*[num_arrays];
        int size_current_array = 0;
    
        for (int i = 0; i < num_arrays; i++)
        {
            std::cin >> size_current_array;
            int *tmp_array = new int[size_current_array];
            for (int j = 0; j < size_current_array; j++)
            {
                int tmp = 0;
                std::cin >> tmp;
                tmp_array[j] = tmp;
            }
            array_of_arrays[i] = tmp_array;
        }
    
    
        //Process the Queries
        int x, y;
        x = y = 0;
        for (int q = 0; q < num_queries; q++)
        {
            std::cin >> x >> y;
            //std::cout << "Current x & y: " << x << ", " << y << "\n";
            std::cout << array_of_arrays[x][y] << "\n";
        }
    
        return 0;
    }
    

    It's a very simple implementation of int main and relies solely on std::cin and std::cout. Barebones, but good enough to show how to work with simple multidimensional arrays.

提交回复
热议问题