Monday, 15 February 2010

c - Failed to create a simulated 2D dynamic array in a structure -



c - Failed to create a simulated 2D dynamic array in a structure -

struct level_info { char **map; } level[level_amount]; (int cnt_1 = 0; cnt_1 < level_amount; cnt_1++) { level[cnt_1].map = malloc(rbn_col * sizeof(char*)); (int cnt_2 = 0; cnt_2 < rbn_col; cnt_2++) level[cnt_1].*(map+cnt_2) = malloc(rbn_row * sizeof(char)); /* line 10 */ }

gcc says: expected identifier before 「*」 token @ line 10, how prepare it?

replace

level[cnt_1].*(map+cnt_2) = malloc(rbn_row * sizeof(char));

with

*(level[cnt_1].map+cnt_2) = malloc(rbn_row * sizeof(char));

or

level[cnt_1].map[cnt_2] = malloc(rbn_row * sizeof(char));

as sizeof(char) defintion 1 do

level[cnt_1].map[cnt_2] = malloc(rbn_row);

or remain flexible in terms of map points do

level[cnt_1].map[cnt_2] = malloc(rbn_row * sizeof(level[cnt_1].map[cnt_2][0]));

additionally please note prefered type index arrays size_t, not int.

so snippet should like:

struct level_info { char ** map; } level[level_amount]; (size_t cnt_1 = 0; cnt_1 < level_amount; ++cnt_1) { level[cnt_1].map = malloc(rbn_col * sizeof(level[cnt_1].map[0])); (size_t cnt_2 = 0; cnt_2 < rbn_col; ++cnt_2) { level[cnt_1].map[cnt_2] = malloc(rbn_row * sizeof(level[cnt_1].map[cnt_2][0])); } }

c pointers

No comments:

Post a Comment