cmultidimensional-arrayundefined-behaviorindexoutofrangeexceptionvariable-length-array

4 Dimensional Array - C


What is the problem with the following code? C compiler shows me error: Segmentation fault.

#include <stdio.h> 
#include <math.h>

int main() {
    int n = 4;
    float A[n][n][n][n];
    A[n][n][1][1] = 1;
    A[n][n][1][2] = 0;
    A[n][n][1][3] = -3;
    A[n][n][1][4] = 0;
    A[n][n][2][1] = 1;
    A[n][n][2][2] = 0;
    A[n][n][2][3] = -3;
    A[n][n][2][4] = 0;
    return 0;
}

Solution

  • If you define an array of length N, the access to the last element is at the N-1 index, and the access to the first element is at index 0 because indexes start from 0 and end at N-1.

    So your code should be like this:

    #include<stdio.h> 
    #include<math.h>
    #define N 4
    
    int main() {
        float A[N][N][N][N];
        A[N-1][N-1][0][0]=1;
        A[N-1][N-1][0][1]=0;
        A[N-1][N-1][0][2]=-3;
        A[N-1][N-1][0][3]=0;
        A[N-1][N-1][1][0]=1;
        A[N-1][N-1][1][1]=0;
        A[N-1][N-1][1][2]=-3;
        A[N-1][N-1][1][3]=0;
        return 0;
    }
    

    Also, you're using a variable to define the length of your array, which is good only in the C99 standard and onwards. If you don't need a VLA (variable length array), you should use the #define instead.