I'm trying to make a 2D array in C with malloc for "hash map" project but as usual. something happend !
basically I have an issue of accessing the 3rd element of the 1st array arr[0][3], it's super weird (at least to me) ,so let me show you the code
1- create 2D array:
int main(void){
char*** table;
table = malloc(sizeof(char*) * 10);
//create array inside table
table[0] = malloc(sizeof(char) * 20);
return 0;
}
2- assign some strings to 1st array table[0]:
table[0][1] = "test1";
table[0][2] = "test2";
table[0][3] = "test3";
table[0][4] = "test4";
...
table[0][n] = "testn";
3- now the magic happens:
// 10 => n >= 0;
printf("%s", table[0][n]);
returns -> malloc(): corrupted top size Aborted (core dumped)
in that moment I tried everything a noob would do , so somehow I figured out that the 3rd string test3 is the problem.
so if I remove the table[0][3] line, all works great !!
table[0][1] = "test1";
table[0][2] = "test2";
//table[0][3] = "test3";
table[0][4] = "test4";
...
table[0][n] = "testn";
// 10 => n >= 0;
printf("%s", table[0][n]);
returns => "testn";
EDIT
for Vlad From Moscow
that works:
for(int i=0; i<10; i++{
table[0][n] = "test";
//here works
printf("%s", table[0][n];
}
//here also works fine
printf("%s", table[0][3];
char*** table;is correct, and you want an array of arrays of strings (a "3d" array), then your allocations are wrong. For examplemalloc(sizeof(char) * 20)will allocate enough space for 20 characters, not pointers tochar. It's similar tochar array[20]. You make the same problem with the other allocation as well, but there it works because a pointer is a pointer, no matter if it'schar *orchar **.2d_arr=[["test"], ["test1","test2"]]