c - Segmentation Fault, large arrays -


#include <stdio.h> #define n 1024 int main(){   int i, j;   int a[n][n];   int b[n][n];   (i=0;i<n;i++){     a[i][i]=i;     b[i][i]=i;   }   (i=0;i<n;i++)     for(j=0;j<n;j++)     {          printf("%d", a[i][j]);          printf("%d", b[i][j]);     }   return 0; } 

this program reason of segmentation fault, if define n 1023, program work correctly. why happens?

you overflowing stack. 2 * 1024 * 1024 * sizeof(int) lot systems.

the simplest solution make arrays static.

static int a[n][n]; static int b[n][n]; 

other methods:

  • make arrays global (this same above)
  • use malloc in loop , of course remember free

    int **a = malloc(n * sizeof *a); (i = 0; < n; i++)     a[i] = malloc(n * sizeof *a[i]); 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -