0

Ok so I have this code to have users input numbers into an array but would like to make it into a function. I am new to C++ and am unsure how to go about it. Can anyone give me some hints or tips? I would greatly appreciate it. The code is as follows:

main()
{
 int m;
 int n;
 int i;
 int j;
 int A[100][100];

 m = get_input ();
 n = get_input2 (); 

 cout << endl << "Enter positive integers for the elements of matrix A:" << endl;

 for (i = 0 ; i < m ; i++)
     for (j = 0 ; j < n ; j++)
         cin >> A[i][j];
return;
}
2
  • 1
    The main point is you'll need to new the memory for the array, not define it on the stack, then free it afterwards. Pass in the dimensions, return the newed data, then call delete[] on it when you're done. (Unless you want to also pass in the allocated array? In which case you can use local variables for that too.) Commented Sep 27, 2014 at 15:25
  • Does it have to be an array specifically? In C++, the idiomatic way to do this would be to use a std::vector. What do you intend to do with the array after? Do you need to do anything other than access elements by [] []? It's usually better to avoid delete in C++. Commented Sep 27, 2014 at 15:29

1 Answer 1

1
void initialize(int x[][], int m, int n){
    cout << endl << "Enter positive integers for the elements of matrix A:" << endl;

    for (int i = 0 ; i < m ; i++)
       for (int j = 0 ; j < n ; j++)
       cin >> x[i][j];
}

main()
{
    int A[100][100],m,n;

   // m = get_input ();// you must have that method or cin>>m
    //n = get_input2 (); //you must have that method or cin>>n
     cout<<"Enter no of rows";
     cin>>m;
     cout<<"Enter no of columns";
     cin>>n;
    initialize (A,m,n);
    return;
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.