-1

I want to sum the matrix on the third row by using a function but it didn't output anything.

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int m = 5, n = 7;

void sumrow ( int *i , int *j ){
      int sum = 0;
      int **a = new int *[m];
      for(int j = 0 ; j < n ; j ++)
          a[*i] = new int [n];
          sum = sum + a[2][*j]; 
       cout << sum << endl;
}
int main () {
       srand (time(NULL));
       int sum = 0;
       int **a = new int *[m];
    for ( int i = 0 ; i < m; i++){
       a[i] = new int [n];
         for( int j = 0; j < n ; j++)
          a[i][j] = rand() % 10;
     }

    for( int i = 0; i < m ; i ++){
         for(int j = 0 ; j < n ; j ++){
            cout << a[i][j] << " ";
      }
       cout << endl;
     }

     int i , j;
       sumrow(&i,&j);

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

I have a problem with the function (sumrow). how can i do it to output the sum in the third row?

Napole
  • 11
  • 2
  • In the `sumrow` function you create a "matrix" `a`, but you never fill it with values. Its contents will be *indeterminate* and using such values will lead to *undefined behavior*. I recommend you invest in [some good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and take some classes to learn C++ properly. – Some programmer dude Dec 20 '20 at 15:54

1 Answers1

0

I suppose you are trying to sum the matrix created in main. The way to do that is to pass the matrix as a parameter from main to sumrow. Not to create a totally different matrix in sumrow. Something like this

int sumrow(int** a)
{
    int sum = 0;
    for (int j = 0; j < n; j++)
        sum = sum + a[2][j]; 
    return sum;
}

int main()
{
    ...
    cout << sumrow(a) << '\n';
    ...
}
john
  • 85,011
  • 4
  • 57
  • 81