446,194 Members | 829 Online
Need help? Post your question and get tips & solutions from a community of 446,194 IT Pros & Developers. It's quick & easy.

# Does this use dynamic two-dimension array correctly?

 P: n/a Do the following two functions use dynamic two-dimension array correctly? #include #include #define ROW 3 #define COL 5 int dyn2dary(void); int dyn2dary_2(void); int main(void) { dyn2dary(); printf("%c", '\n'); dyn2dary_2(); return 0; } int dyn2dary(void) { int r = 0, c = 0; char *p = malloc(ROW * COL * sizeof *p); if (!p) return -1; for (r = 0; r < ROW; r++){ for (c = 0; c < COL; c++){ p[r * COL + c] = 'a' + r * COL + c; printf("%c ", p[r * COL + c]); } printf("%c", '\n'); } free(p); return 0; } int dyn2dary_2(void) { int r = 0, c = 0; char (*a)[COL]; char *p = malloc(ROW * COL * sizeof *p); if (!p) return -1; a = (char (*) [COL])p; for (r = 0; r < ROW; r++){ for (c = 0; c < COL; c++){ a[r][c] = 'a' + r * COL + c; printf("%c ", a[r][c]); } printf("%c", '\n'); } free(a); return 0; } Jun 10 '07 #1