user12290
user12290

Reputation: 643

Four Dimensional Integer Array in C

I want to use array of 4 dimension.

int A[80][80][80][80];

When I try to use it I get Segmentation fault (core dumped). For example:

for(i=0;i<80;i++)
 for(j=0;j<80;j++)
   for(k=0;k<80;k++)
    for(l=0;l<80;l++)
         A[i][j][k][l]=i+j+k+l;

printf("%d\n",A[0][1][2][3]);

Upvotes: 0

Views: 110

Answers (1)

simonc
simonc

Reputation: 42165

That's a pretty huge array - 40,960,000 * sizeof(int) bytes. If you're declaring it on the stack, you're sure to be overflowing available stack memory. Try heap allocating it instead.

int* A = malloc(80 * 80 * 80 * 80 * sizeof(int));
/* use A */
free(A);

Or, better, as John Bode suggested

int (*A)[80][80][80] = malloc( sizeof *A * 80 );

for (i=0; i<SIZE; i++) {
    for (j=0; j<SIZE; j++) {
        for (k=0; k<SIZE; k++) {
            for (l=0; l<SIZE; l++) {
                A[i][j][k][l] = i+j+k+l;
            }
        }
    }
}
printf("%d\n",A[0][1][2][3]);

free(A);

Upvotes: 7

Related Questions