Search code examples
c++pointersdynamic-memory-allocation

C++ creating an array pointing to different arrays


The inputs to this program are as follows:

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

I would like n to be an array that points to other integer arrays. So, n should essentially be {{1, 5, 4}, {1, 2, 8, 9, 3}}. If I wanted to access the 0th array and the 1st index, the value should return 5, and if I were to access the 1st array and the 3rd index, the value should be 9.

However, the values that this code returns are 32764 and 32764.

#include <cstdio>
#include <iostream>
using namespace std;

int main() {
    int n_l; // integer variable that will hold the length of array n
    int q_l; // integer variable that will hold the length of the number of queries
    cin >> n_l >> q_l; // assigns values to the variables n_l and q_l
    int *n[n_l]; // creates an array that will contain pointers
    for (int i = 0; i < n_l; i++){ // loops through the length of array n 
        int amount; // declares the variable amount
        cin >> amount; // assigns a value to the variable amount
        int k[amount]; // creates one of the arrays that will be added to n
        for (int x= 0; x < amount; x++){ // loops through the length of k and assigns a value to each index
            cin >> k[x];
        }
        n[i] = k; // adds the array k to the position in array n
    }
    
    for (int i = 0; i < q_l; i++){
        int arraynum;
        int index;
        cin >> arraynum >> index;
        cout << n[arraynum][index] << endl;
    }   
}

Solution

  • cin >> n_l >> q_l; // assigns values to the variables n_l and q_l
    int *n[n_l];
    

    This isn't allowed in C++. The size of an array variable must be compile time constant. You can create dynamic arrays. Most convenient way is to use std::vector class template from the standard library.

    The issue with your pointers is that the automatic arrays that you create in the loop are automatically destroyed at the end of the loop statement and the pointers in the array are all dangling (i.e. invalid) pointers to destroyed arrays. When you later indirect through the invalid pointers, the behaviour of the program is undefined.

    You want multiple arrays. What's a good way to create multiple objects? Array is a good way to create multiple objects. So, in order to create multiple arrays, you can create an array of arrays. Or, since you want dynamic sizes, you can create a vector of vectors. Here is an example of how to create a vector of vectors:

    std::vector<std::vector<int>> n(n_l);
    for(auto& vec : n) {
        int amount;
        std::cin >> amount;
        vec.resize(amount);
        for(auto& i : vec) {
            cin >> i;
        }
    }
    

    You could create a vector of pointers to the arrays within the vectors in the vector of vectors, but that would be pointless. You don't need the pointers.