Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#include <iostream>
using namespace std;

int i, j;


void read(int** theArray, int numberOfRows, int numberOfColumns)
{

    for (i = 0; i < numberOfRows; i++)
            {
                for (j = 0; j < numberOfColumns; j++)
                    {
                        cout<<"\nEnter element ["<<i+1<<"]["<<j+1<<"]: ";
                        cin>>theArray[i][j];
                    }  
            }
}


int main()
  {
    int a, b;
    a=b=0;
    cout<<"row ";
    cin>>a;
    cout<<"col ";
    cin>>b;
    //int Arr;
    int** Arr = new int*[a];
    for (i = 0; i < a; i++)
      {
        Arr[i] == new int[b];
      }
    
    read(Arr, a, b);

    for(int i = 0; i < a; i++)
      delete[] Arr[i];
    delete[] Arr;
    return 0;
  }


What I have tried:

I'm trying to read elements for a 2-D array.
It is a user input program.
Shows Segmentation fault error.
Posted
Updated 3-Apr-22 20:26pm

warning C4553: "==": Operator
C++
Arr[i] == new int[b];


Nonsensical instruction, right?
 
Share this answer
 
Why bothering about memory management when the standard library provides the vector class?
C++
#include<iostream>
#include <vector>

using namespace std;

void read_all( vector < vector < int > > & v)
{ 
  for (size_t r = 0; r < v.size(); ++r) 
    for (size_t c = 0; c < v[r].size(); ++c)
    { 
      cout << "please enter item [" << (r+1) << "][" << (c+1) << "]: ";
      cin >> v[r][c];
    }
}

int main()
{
  size_t rows, cols;
  cout << "please enter the number of rows: ";
  cin >> rows;
  cout << "now enter the number of columns: ";
  cin >> cols;

  vector < vector <int> > v(rows);

  for (size_t r = 0; r < rows; ++r)
    v[r] = vector<int>(cols);

  read_all(v);

  for (const auto & vr : v)
  {
    for (const auto & x : vr)
      cout << x << " ";
    cout << "\n";
  }
}
 
Share this answer
 
Comments
jeron1 4-Apr-22 20:13pm    
:thumbsup: Indeed!
CPallini 5-Apr-22 11:37am    
Thanks.
:-)
Apoorva Jadhav 5-Apr-22 11:40am    
Having an assignment and had to do using memory management method. 😅😅. Thank you for your help 😊

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900