2D dynamic array problem

Hi guys,
I am new to C++ and I am having trouble to write a function that return an array by summing up the element of each row from a 2D array .here is the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
using namespace std;

int* sum(int*p, int row, int col);


int* sum(int*p, int row, int col)
{
	int*m = new int[row];
	for(int i=0; i<row; i++)
	{
		int sum=0;
		for(int j=0; j<col; j++)
		{
			sum =+ p[i][j]; //I don't know what is wrong with j
		}
		m[i]=sum;
	}
	return m;
}
void main(){
	int row,col;
	cin>>row>>col;
	int**m=new int*[row];
	for(int i=0; i<row; i++)
		m[i]=new int[col];
	for(int i=0; i<row; i++)
		for(int j=0; j<col; j++)
			cin>>m[i][j];  
	int* result= sum(*m,row, col);
	for(int i = 0; i<row; i++)
		cout<<result[i];
	

}

Last edited on
Can someone told me what's wrong with the j?

minor tweaks at line nos 7,15,30, there is no need for declaration if you are defining a function before main func.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int* sum(int**p, int row, int col)
{
	int*m = new int[row];
	for(int i=0; i<row; i++)
	{
		int sum=0;
		for(int j=0; j<col; j++)
		{
			sum += p[i][j]; //its += not =+ 
		}
		m[i]=sum;
	}
	return m;
}
void main(){
	int row,col;
	cin>>row>>col;
	int**m=new int*[row];
	for(int i=0; i<row; i++)
		m[i]=new int[col];
	for(int i=0; i<row; i++)
		for(int j=0; j<col; j++)
			cin>>m[i][j];  
	int* result= sum(m,row, col);
	for(int i = 0; i<row; i++)
		cout<<result[i];
	

}

thanks a lot
Topic archived. No new replies allowed.