c++ - 段错误[二维数组]

标签 c++ multidimensional-array segmentation-fault

#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";
  }
}

输入格式:

没有。试验

没有。行数(空格)没有。列数

第 1 行(没有空格,只有 1 或 0)

第二行...

输出:

二维数组

总人数在每列中选择两个的方法

问题:

程序显示数组足够好。

但是遇到 calc_Collision(A) 时,代码输出:

段错误(核心转储)

不显示“FLAG”。

这里仍然是初学者,所以任何帮助将不胜感激。

最佳答案

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));
  }
}

请注意,如果 select 中的 x 小于 2,则 fact(x-y) 将无限期地调用自身。这是因为 fact 中的变量 a 将为负数。当输入数组的大小少于 10 列时会发生这种情况,导致最后一列变为空。这导致 count 的迭代在 calc_Collision 中变为 0。如果输入有 10 列,则不会发生段错误。 由于您只计算 nC2(N 选择 2),select 函数可以重写为:

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

关于c++ - 段错误[二维数组],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39349574/

相关文章:

c++ - 函数中有函数原型(prototype)的目的是什么?

c++ - 在 visual studio 中创建了一个空项目,它似乎不再打开控制台?

c++ - 下面的 std::move 是多余的吗?

c - 在C中打开文件进行读取

c - 我的段错误发生在哪里?

c++ - 提取文件名的子字符串

c - 数组打印值的总和

java - 当我尝试设置 clickListener 时,应用程序崩溃

javascript - 在多维数组中搜索值

c++ - 具有一个版本的等效代码的 SegFault?