c - 为什么当 n>500 时会出现段错误?用 C 编码

标签 c segmentation-fault

下面是我为 Euler 项目中的问题 28 编写的代码。它需要沿着一个由递增数字组成的扩展正方形的两条对角线将数字相加。当我设置num>500时,它会导致段错误。在此限制之前,它可以完美运行。提前致谢!

#include <stdio.h>

int main(){

  int n, num=501;
  int array[num-1][num-1];
  int p=((num+1)/2)-1;
  int count=25;
  int x;

    array[p][p]=1;
    array[p+1][p]=4;
    array[p+1][p+1]=3;
    array[p][p+1]=2;
    array[p-1][p+1]=9;
    array[p-1][p]=8;
    array[p-1][p-1]=7;
    array[p][p-1]=6;
    array[p+1][p-1]=5;  

    int i=10; 
  for (n=2;((n*2)+1)<=num;n++){



    for(x=0;x<n*2;x++){
       array[p+(x-(n-1))][p+n]=i;
       i++;
    }
    count+=(i-1);



    for(x=0;x<n*2;x++){
      array[p+n][p+(n-1)-x]=i;
      i++;
    }
          count+=(i-1);




    for(x=0;x<n*2;x++){
      array[p+((n-1)-x)][p-n]=i;
      i++;
    }
     i--;


        count+=i;
    for(x=0;x<=n*2;x++){
      array[p-n][p+(x-n)]=i;
      i++;
    }

        count+=(i-1);
 }

    printf("The answer is %lu\n", count);

}

最佳答案

我最好的猜测是,因为 500*500*sizeof(int) == 1000000 (假设 sizeof (int) == 4),你已经运行堆栈空间不足。我建议将其放在堆上:

typedef struct { int array[num - 1][num - 1] } arr;

int main(void)
{
    const int num = 501;
    int n;
    arr *array;
    int p = (num + 1) / 2 - 1;
    int count = 25;
    int x;

    array = malloc(sizeof arr);

    array->array[p][p] = 1;
    array->array[p + 1][p] = 4;
.
.
.

关于c - 为什么当 n>500 时会出现段错误?用 C 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37426558/

相关文章:

c - 为什么在创建 pthread 时会出现段错误?

c - K&R 练习 1-19 意外且不一致的输出

c - 指针数组元素中有错误(不需要的)值

c - 使用 libblkid 时出错

c++ - 如何正确声明和初始化一个字符数组?

gcc - 无法在 Ubuntu 10.04 上构建 Node.js

c - int A[]={} 在 C 中是什么意思?

c - C 中存储 char 的动态数组

c++ - 析构函数末尾的段错误

c++ - 为什么在我的程序中出现段错误?