Dynamic allocation giving problem in c ++

1

I have this problem to solve in Hacker Rank and my code for solving this problem was as follows:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int **arr, arrqtd, queries;

    cin >> arrqtd >> queries;

    arr = (int **) malloc(sizeof(int)*arrqtd);  
    for (int i = 0; i < arrqtd;i++){
        int size;

        cin >> size;
        arr[i] = (int *) malloc(sizeof(int)*size);

        for(int j = 0; j < size;j++){
            int value;
            cin >> value;
            arr[i][j] = value;
        }
    }

    for (int i = 0; i < queries;i++){
        int row,col;
        cin >> row >> col;
        cout << arr[row][col] << endl;
    }
    return 0;
}

The problem is that in an example input like this:

10 10
3 916135 272188 794963
3 178997 502468 671251
1 122266
3 223511 996043 990104
3 319694 335208 200789
2 867809 273793
1 925358
1 71140
1 862238
1 994309
6 0
5 0
5 0
7 0
5 0
6 0
3 2
3 1
0 0
9 0

The initial value of my array changes from the sixth iteration, I would like to know what I did wrong but so far I have not found anything (and I would also like to know why this initial value changes from "nothing").

    
asked by anonymous 02.03.2018 / 17:24

1 answer

3

In fact, you have a very small subtle error in your program, and it is in the memory allocation of the two-dimensional array:

arr = (int **) malloc(sizeof(int)*arrqtd);  

What should be

arr = (int **) malloc(sizeof(int*)*arrqtd);  
//------------------------------^

You are making an array of pointers, so it is the sizeof of int* that matters. It will only make a difference on a machine where the int size is different from int* , so you may not encounter the error depending on where you run the code.

With this change the program produces the desired output:

925358
867809
867809
71140
867809
925358
990104
996043
916135
994309

Confirm on Ideone

Recommendations:

Unless for educational purposes, it will be more appropriate to use either <vector> or new int[] as @ JeffersonQuesado mentioned for 2 reasons:

1 - Because they become much simpler and avoid mistakes such as this one had.

2 - They are more idiomatic in the C ++ world. The code you wrote is basically C code using couts and cins

    
02.03.2018 / 19:05