i've been reading learn c hard way few days, here's want understand. zed, author, wrote char **
"pointer (a pointer char)", , saying needed because i'm trying point 2-dimensional.
here what's written in webpage
a char * "pointer char", that's string. need 2 levels, since names 2-dimensional, means need char ** "pointer (a pointer char)" type.
does mean have use variable can point 2-dimensional, why need 2 **
?
just little follow-up, apply n dimension?
here's relevant code
char *names[] = { "alan", "frank", "mary", "john", "lisa" }; char **cur_name = names;
no, tutorial of questionable quality. wouldn't recommend continue reading it.
a char**
pointer-to-pointer. not 2d array. not pointer array. not pointer 2d array.
the author of tutorial confused because there wide-spread bad , incorrect practice saying should allocate dynamic 2d arrays this:
// bad! not this! int** heap_fiasco; heap_fiasco = malloc(x * sizeof(int*)); for(int x=0; x<x; x++) { heap_fiasco[x] = malloc(y * sizeof(int)); }
this not 2d array, slow, fragmented lookup table allocated on heap. syntax of accessing 1 item in lookup table, heap_fiasco[x][y]
, looks array indexing syntax, therefore lot of people reason believe how allocate 2d arrays.
the correct way allocate 2d array dynamically is:
// correct int (*array2d)[y] = malloc(sizeof(int[x][y]));
you can tell first not array because if memcpy(heap_fiasco, heap_fiasco2, sizeof(int[x][y]))
code crash , burn. items not allocated in adjacent memory.
similarly memcpy(heap_fiasco, heap_fiasco2, sizeof(*heap_fiasco))
crash , burn, other reasons: size of pointer not array.
while memcpy(array2d, array2d_2, sizeof(*array2d))
work, because 2d array.
Comments
Post a Comment