Problem : I am trying to initialize a square 2d array and find the absolute difference of the sum of its diagonals. I have written following code for that purpose.
#include<vector>
#include<iostream>
using namespace std;
vector<vector<int>> init() // function to initialize the array
{
int size;
cin>>size;
vector<vector<int>> vector(size);
for(int i = 0; i < size; ++i)
{
vector[i].resize(size);
for(int j = 0; j < size; ++j)
{
cin>>vector[i][j];
}
}
return vector;
}
int diagonal_diff(vector<vector<int>> vector)// function to find difference
{
int diff;
auto sum_1 = 0;
auto size = vector.size();
for(auto i = 0; i < size; ++i)
{
auto j = i;
sum_1 = vector[i][j] + sum_1;
}
int sum_2 = 0;
for(auto i = size -1; i >= 0; --i)
{
auto j = (size-1) - i;
sum_2 = vector[i][j] + sum_2;
}
diff = sum_1 - sum_2;
diff = (diff >= 0)? diff:diff*(-1);
return diff;
}
int main()
{
auto vector = init();//initialising array
for(auto i = 0; i < vector.size(); ++i)//printing the array
{
for(auto j = 0; j < vector.size(); ++j )
{
cout<< vector[i][j];
}
}
auto temp = diagonal_diff(vector);// calling difference function
cout<<temp<<endl;
return 0;
}
but it gives segmentation Fault after printing the array. can't figure out what the cause is.
I was trying to solve this problem from hackerRank. If I comment out the line which calls the diagonal_diff() function then the code runs fine. So I think the error is in diagonal_diff() function.