0

I'm trying to write and read a char three dimensional array, or said in other words an array of strings arrays.

I've already try to allocate the memory in each part of the array, but it keeps failing with the following error: Segment fault (core dumped)

/**
 * Create array to write
 */
char writed[2][2][512] = {{"Hello", "World"}, {"Bye", "World"}};
/**
 * Allocate memory
 */
char *** readed = (char ***)malloc(sizeof(char **) *2 * 2 * 512);
for (int z = 0; z < 2; z++) {
    readed[z] = (char **)malloc(sizeof(char **) * 2 * 512 );
    for (int y = 0; y < 2; y++) {
        readed[z][y] = (char *)malloc(sizeof(char) * 512); 
    }
}    
/**
 * Write array
 */
FILE *writeFile = fopen("strings", "wb");
fwrite(writed, 2 * 2 * 512, 2 * 512, writeFile);
fclose(writeFile);
/**
 * Read array
 */
FILE *readFile = fopen("strings", "rb");
fread(readed, 2 * 2 * 512, 2 * 512, readFile);
fclose(readFile);

1 Answers1

1

You have two different data structures here, each with a different layout.

writed is a 3 dimensional array of char, meaning that all of the memory of the array is contiguous. In contrast, readed is a pointer to an array of char **, each of which points to an array of char *,each of which points to an array of char, and none of those need be continuous.

To have a similar data structure, you need declare readed as a pointer to a 2D array and allocate space for enough of those for a 3D array:

char (*readed)[2][512] = malloc(2 * sizeof(char[2][512]));

Also, don't cast the return value of malloc.

You're also writing / reading way more than you need to:

fwrite(writed, 2 * 2 * 512, 2 * 512, writeFile);
...
fread(readed, 2 * 2 * 512, 2 * 512, readFile);

This says you're reading / writing 2 * 512 elements, each of which has size 2 * 2 * 512. You're only reading/writing 1 member of that size:

fwrite(writed, 2 * 2 * 512, 1, writeFile);
...
fread(readed, 2 * 2 * 512, 1, readFile);
dbush
  • 186,650
  • 20
  • 189
  • 240