Rahul R Rahul R - 3 months ago 13
C++ Question

Segmentation Fault [2D array]

#include <iostream>

using namespace std;

void input_Array(char (&A)[10][10], int x, int y);
int calc_Collision(char (&A)[10][10]);
void display(char (&A)[10][10]);
void init_Array(char (&A)[10][10]);

int main()
{
int m,n,test;
char A[10][10];
init_Array(A);
cin>>test;
while (test>0)
{
cin>>m>>n;
input_Array(A,m,n);
display(A);
cout<<"FLAG";
cout<<calc_Collision(A);
test--;
}
}

//Calculates no. of ways to select two 1's in each column
int calc_Collision(char (&A)[10][10])
{
int count=0;
int sum=0;
int select(int x, int y);
for (int j = 0; j<10; j++)
{
count=0;
for(int i = 0; i<10; i++)
{
if (A[i][j]=='1')
{
count++;
}
}
sum=sum + select(count,2);
}
return sum;
}

//Returns no. of ways to select y items from x items
int select(int x, int y)
{
int fact(int a);
return (fact(x)/(fact(y)*fact(x-y)));
}

//Returns a!
int fact(int a)
{
if (a==0)
{
return 1;
}
else
{
return (a*fact(a-1));
}
}

void display(char (&A)[10][10])
{
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
{
cout<<A[i][j]<<"\t";
}
cout<<"\n";
}
}


Input Format:



no. of trials

no. of rows (whitespace) no. of columns

row1 (No space, 1's or 0's only)

row2...

Output:



The 2D array

Total no. of ways to select two one's in each column

Problem:



The program displays the array fine enough.

But upon coming across calc_Collision(A), the code outputs:

Segmentation fault (core dumped)

"FLAG" is NOT displayed.

Still a beginner here, so ANY help would be appreciated.

Answer
int select(int x, int y){
  int fact(int a);
  return (fact(x)/(fact(y)*fact(x-y)));
}


int fact(int a){
  if (a==0)  {
    return 1;
  }
  else  {
    return (a*fact(a-1));
  }
}

Notice that if x in select is less than 2, then fact(x-y) will call itself indefinitely. This is because the variable a in fact will be negative. This occurs when the size of the input array has less than 10 columns, resulting in the last column becoming empty. This causes the iteration of count to become 0 in calc_Collision. The segmentation fault does not occur if the input has 10 columns. Since you are only computing nC2 (N choose 2), the select function can be rewritten as:

int select(int x){
  return (x*(x-1))/2;
}