You can sometimes see code like that:
# Bad code int * my_array[NUM]; int * sub_array = malloc(sizeof(sub_array[0]) * SUB_NUM); if (! sub_array) { /* Handle out-of-memory */ } for (int i = 0 ; i < NUM ; i++) { populate_sub_array(i, sub_array); my_array[i] = sub_array; }
The problem with code like this is that the same physical memory location is being used in all places in the array, and so they will always be synchronised to the same contents.
As a result, the code excerpts should be written as such instead:
int * my_array[NUM]; for (int i = 0 ; i < NUM ; i++) { int * sub_array = malloc(sizeof(sub_array[0]) * SUB_NUM); if (! sub_array) { /* Handle out-of-memory */ } populate_sub_array(i, sub_array); my_array[i] = sub_array; } my @array_of_arrays = map { [] } (1 .. $num_rows);