Creating a funtion that return a memory adress

I gotta implement a code where I need to enter a certain matrix A(5x5) and then call a function that returns a pointer ta a array B that contains the sum of each column of the matrix;

kinda like that :
input:

1 2 3 4 5
5 4 3 2 1
1 1 1 1 1
2 2 2 2 2
9 8 7 6 5

output:

18 17 16 15 14

so, I'm super lost when it comes to "return a pointer" that points to that array B.

Ps.: the array B must be allocated dynamically

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
#include<iostream>
using namespace std;

int arrB(int A[][]){//is this parameter right? or should be A[5][5]
    int* B = new int[5];
    
    for (int i = 0; i < 5; i++){
        int sum =0;
	for (int j = 0; j < 5; j++){
            sum+=A[j][i];
        }
        B[i]= sum;
     }
     return ??;

}

int main(){

    int A[5][5];
    
    for (int i = 0; i < 5; i++){
        for (int j = 0; j < 5; j++){
            cin >>A[i][j];
        }
    }
    
    arrB(A);
   
    delete[] B;
    
    return 0;
    }
Last edited on
You're pretty close. Here is your program modified to work.

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
#include<iostream>
using namespace std;

constexpr size_t N=5;		// Make the size a constexpr so you can change it easily


int *
arrB(int A[N][N])
{
    int *B = new int[N];

    for (size_t i = 0; i < N; i++) {
	int sum = 0;
	for (size_t j = 0; j < N; j++) {
	    sum += A[j][i];
	}
	B[i] = sum;
    }
    return B;
}

int
main()
{

    int A[N][N];

    for (size_t i = 0; i < N; i++) {
	for (size_t j = 0; j < N; j++) {
	    cin >> A[i][j];
	}
    }

    int *B = arrB(A);

    // print B array
    for (size_t i=0; i<N; ++i) {
	cout << B[i] << ' ';
    }
    cout << '\n';

    delete[]B;
    return 0;
}

Perfect! I was not getting how to return a pointer but now I got it! thanks!
Topic archived. No new replies allowed.