1

So basically I am trying to read from a huge text file and need to store the data in a 2D string array in C. But I am getting a segmentation fault every time.

Here is the code I use to create the array:

Y = 3
X = 12
char ***some_array=NULL;
some_array = (char ***)malloc(Y * sizeof(char *));
    for (int i=0; i<Y; i++)
        for (int j=0; j<X; j++){
            some_array[i] = (char **)malloc(X * sizeof(char *));
            some_array[i][j] = (char *)malloc(16 * sizeof(char));
        }

So technically, I am creating a 3D char array for this means. Am I doing something wrong here?

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Socrates
  • 335
  • 2
  • 3
  • 11
  • *So technically, I am creating a 3D char array...* No, you're creating a one-dimensional array of pointers to multiple one-dimensional arrays of pointers to multiple one-dimensional arrays of `char[16]`. – Andrew Henle Dec 26 '20 at 14:37

2 Answers2

1

Error is in your loop:

for (int i=0; i<Y; i++) {
    some_array[i] = (char **)malloc(X * sizeof(char *));
    for (int j=0; j<X; j++){
        some_array[i][j] = (char *)malloc(16 * sizeof(char));
    }
}

You are supposed to allocate memory to some_array[i] outside the inner loop.

Jarvis
  • 8,494
  • 3
  • 27
  • 58
1

You need to move the allocation of some_array[i] = (char **)malloc(X * sizeof(char *)); from the inner most loop to the outer loop. Moreover, you should not cast the malloc return value. For the final code:

Y = 3
X = 12
char ***some_array = NULL;
some_array = malloc(Y * sizeof(char *));
    for (int i = 0; i < Y; i++){
        some_array[i] = malloc(X * sizeof(char *));
        for (int j = 0; j < X; j++){
            some_array[i][j] = malloc(16 * sizeof(char));
        }
    }

Alternatively you can create a statically allocated array:

char some_array [X][Y][16];
dreamcrash
  • 47,137
  • 25
  • 94
  • 117