Why if I change the size of one of the dimensionality of an array I get a run-time Error: "Segmentation Fault?". Example:
#include <stdio.h>
#define DIM 8
int main(int argc, char **argv)
{
int a[3][3][3][3][3][3][3][3][3][3][DIM],
b;
a[1][1][1][1][1][1][1][1][1][1][1] = 2;
b=a[1][1][1][1][1][1][1][1][1][1][1];
printf("%d \n",b);
return 0;
}
If DIM is 8 it generated no run-time error, but just if DIM is greater than 8, it causes run-time Error "Segmentation Fault". Why ???
Almost certainly a stack overflow. You are allocating, what, 3 ^ 10 * 9 * sizeof(int) bytes! Use int *a = (int*)malloc(N * sizeof(int)) instead, where N is the number of ints you want. Then you can simulate an N-dimensional array on it.
I'll explain how to simulate a 2D array on a 1D array.. Say it has rows of width 10. Then you access the 5th value on row three by taking a[10 * 2 + 5]. In general, you do a[width * (row - 1) + column].
Second method. You can allocate an array of pointers to pointers of ints:
int **a = (int**)malloc(rows * sizeof(int*))
for (int i=0; i<row; ++i)
a[i] = (int*)malloc(columns * sizeof(int))
... extending this to more dimensions left as an exercise for the reader.
3*3*3*3*3*3*3*3*3*3*8 = 472392; 472392*4 /* sizeof (int) */ = 1889568 3*3*3*3*3*3*3*3*3*3*9 = 531441; 531441*4 /* sizeof (int) */ = 2125764
I guess your stack is limited to 2Mbytes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With