Home > Blockchain >  How to get input and display 2 dimensional array in c ?
How to get input and display 2 dimensional array in c ?

Time:10-28

Code:-

    #include <iostream> 
    using namespace std;
    
    int main() {
        int r,c,*p;
        cout<<"Rows : ";
        cin>>r;
        cout<<"Columns : ";
        cin>>c;
        
        p=new int[r*c];
        
        cout<<"\nEnter array elements :"<<endl;
        int i,j,k;
        for( i=0;i<r;i  ){
          for( j=0;j<c;j  ){
            cin>>k;
            *(p i*c j)=k;
          }
        }
        
        cout<<"\nThe array elements are:"<<endl;
        for( i=0;i<r;i  ){
          for( j=0;j<c;j  ){
            cout<<*p<<" ";
            p=p 1;
          }
          cout<<endl;
        }
        cout<<endl;
        
        delete[]p;
        return 0; 
}

Output:-

Output

Error:-

munmap_chunk(): invalid pointer Process finished with exit code -6.

Can anyone explain why the above error occurs?

CodePudding user response:

The problem occurs at the end of your program, when you delete[] p. In the nested for-loop immediately preceding it, you are modifying p, thus, when attempting to delete[] p at the end, you get undefined behaviour.

Potential fixes include, when printing the array elements, access the pointer the same way you did in the first for loop (or as Jarod mentioned, using [i * c j].

Alternatively, you can use an additional variable.

int *tmp = p;
for( i = 0 ; i < r; i   ){
   for( j = 0; j < c; j   ){
       cout << *tmp << " ";
       tmp = tmp   1; //   tmp; also works
   }
   cout << endl;
}
cout << endl;
        
delete[] p;

This way, p still points to the original address.

  • Related