Adding right diagonals of 2 matrices

Write a program to create 2 dynamically created, 2D Arrays (with equal
rows and columns) of user’s desired size, pass these 2 array to functions
using pointers to add Right diagonal values to 3 rd dynamically created
array and return that array to main functions using pointer.

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
using namespace std;
void adddiognals(int **ptr, int **ptr2,int x, int y)
{
	int *ptr3 = new int[y];
	for (int i = 0; i < x; i++)
	{
		for (int j = 0; j < y; j++)
		{
			if (i = j)
			{
			   ptr3[i]= ptr[i][j] + ptr2[i][j];
			}

		}
	}
	for (int i = 0; i < y; i++)
	{
		cout << ptr3[i];
	}
	
}
int main()
{
	int x, y;
	cout << "1st 2d array:" << endl;
	cout << "Enter rows :" << endl;
	cin >> x;
	int **ptr1 = new int*[x];
	cout << "Enter columns :" << endl;
	cin >> y;
	for (int i = 0; i < x; i++)
	{
		ptr1[i] = new int[y];
	}
	cout << "Enter elements in matrix 1: " << endl;
	for (int i = 0; i <x; i++)
	{
		for (int j = 0; j <y; j++)
		{
			cout << endl;
			cin >> ptr1[i][j];

		}
	}
	int x2, y2;
	cout << "1st 2d array:" << endl;
	cout << "Enter rows :" << endl;
	cin >> x2;
	int **ptr2 = new int*[x2];
	cout << "Enter columns :" << endl;
	cin >> y2;
	for (int i = 0; i < x2; i++)
	{
		ptr2[i] = new int[y2];
	}
	cout << "Enter elements in matrix 2: " << endl;
	for (int i = 0; i <x2; i++)
	{
		for (int j = 0; j <y2; j++)
		{
			cout << endl;
			cin >> ptr2[i][j];

		}
	}
	adddiognals(ptr1, ptr2, x, y);
	system("pasue");


}

Can anyone find the error?
> and return that array to main functions using pointer.
Well you don't return anything.

> (with equal rows and columns)
Why do you prompt for columns then?
Why don't you ensure that both are equal?

Compile with lots of warnings.
1
2
3
4
5
$ g++ -Wall -Wextra foo.cpp
foo.cpp: In function ‘void adddiognals(int**, int**, int, int)’:
foo.cpp:10:13: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
    if (i = j)
             ^


Also, a sea of variables all called ptr,x,y are not descriptive of the problem.

You basically copy/pasted the code to read both matrices, where you should have created a function.

1
2
3
4
5
6
7
8
9
10
int main ( ) {
    int **matrix1, int **matrix2;
    int side;
    cout << "How big";
    cin >> side;
    matrix1 = createMatrix(side);
    matrix2 = createMatrix(side);
    int *diagonalSum = adddiognals(matrix1,matrix2,side);
}


Topic archived. No new replies allowed.