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?

1
  • 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]. Commented Dec 26, 2020 at 14:37

2 Answers 2

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];
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.