Why do I get a seg fault when in n>500? Coded in C -


in following piece of code wrote problem 28 in project euler. needs add numbers along 2 diagonals of expanding square of increasing numbers. results in seg fault when set num>500. until limit works perfectly. in advance!

#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;    (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 %lu\n", count);  } 

my best guess because 500*500*sizeof(int) == 1000000 (assuming sizeof (int) == 4), you've run out of stack space. suggest putting on heap instead:

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; . . . 

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -