Search code examples
c++algorithmpointersmemory-managementdynamic-memory-allocation

Problem for dynamic memory allocation in c++


while i am trying to solve a hackerrank problem,i had a problem in my mind.My problem is i want to allocate some memories with pointers and i made this with two ways,but one of them resulted with the problem.Other one has no problem.

Hackerrank problem is here 1. enter image description here

Hackerrank problem is here 2.enter image description here

Hackerrank problem is here 3.enter image description here

This code worked with no problem.

int x,y,z;
cin>>x>>y;
int *arr[x];
for(int i=0;i<x;i++){
    int z;
    cin>>z;
    arr[i] = new int[z];
    for(int j=0;j<z;j++){
        cin >> arr[i][j]; 
    }
    
}
int *arr2[y];
for(int k=0;k<y;k++){
    arr2[k] = new int[2];
    for(int tt=0;tt<2;tt++){
        cin >> arr2[k][tt];
    }
    
}
for(int i = 0;i<y;i++){
    
        cout<<arr[arr2[i][0]][arr2[i][1]]<<endl;
    
}

My question is here.

**what is the problemlem for making a definition of int *arr = new int[x]; rather than *arr[x] I want to make a new allocation with pointer.Is both of them aren't same ? I didn't understand. ** *If a make a definition of int arr = new int[x]; then the problem is arr[i] = new int[z];

int x,y,z;
cin>>x>>y;
int *arr = new int[x];  **<-- **
for(int i=0;i<x;i++){
    int z;
    cin>>z;
    arr[i] = new int[z];   **<-- problem**
    for(int j=0;j<z;j++){
        cin >> *arr[i][j]; 
    }
    
}
int *arr2 = new int[y];
for(int k=0;k<y;k++){
    arr2[k] = new int[2];
    for(int tt=0;tt<2;tt++){
        cin >> *arr2[k][tt];
    }
    
}
for(int i = 0;i<y;i++){
    
        cout<<*arr[*arr2[i][0]][*arr2[i][1]]<<endl;
    
}


  
return 0;

Solution

  • You are trying to make a matrix (2-dimensional array) from an array. You should write like that:

    int **matrix = new int*[x]; //pay attention to number of asterisks
    for(int i = 0; i < x; ++i)
    {
      matrix[i] = new int[z];
    }
    

    int *arr[x] is similar to int **matrix = new int*[x]. It creates an array of x arrays with undefined size.

    P.S: using pointers in C++ is considered a bad practice. You should use std::vector instead. That's an example:

    std::vector<std::vector<int>> matrix(x);
    for(int i = 0; i < x; ++i)
    {
      matrix[i] = std::vector<int>(z);
    }
    

    P.P.S: don't forget to #include <vector>.