0
I’m having to create a function in a separate file from main. This function will receive the values of a matrix, sum all values per line, store the sum in a vector, and then print the respective vector. However, I am not able to print the desired results. The main archive is ready to receive the matrices.
This is the function code.
#include <iostream>
void sum(float A[], float v[], const short N, const short M)
{
int i,j;
for (j=0; j<M; j++)
{
for ( i=0; i<N; i++)
{
v[i] += A[i*M+j];
}
}
for (i=0; i<N; i++)
{
std::cout << v[i] << " ";
}
}
And this is the main file where I type the matrix, print the matrix and get the function.
#include <iostream>
#include "funcoes.hpp"
using namespace std;
int main()
{
const short n=3,m=4;
float a[n][m];
int i,j;
float v[n],resul;
for( i=0; i<n; i++)
{
for( j=0; j<m; j++)
{
cout << "Digite [" << i+1 << "][" << j+1 << "] : ";
cin >>a[i][j];
}
cout << endl;
}
for( i=0; i<n; i++)
{
for( j=0; j<m; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
sum(&a[n][m],&v[n],n,m);
return 0;
}
It is worth mentioning that I know I could write everything on main. It would be even easier. However, I I need that the function is created outside the main.
What’s wrong with you?
– Shinforinpola
I don’t know why you don’t declare your function parameter as a two-dimensional array. Your function call should be:
sum(a, v, n, m);
.– anonimo
When you do
&a[n][m]
and&v[n]
is referring to the address of the specific position of the array which, by the way, are outside the limits of the array.– anonimo