L
lovecreatesbea...
Do the following two functions use dynamic two-dimension array
correctly?
#include <stdio.h>
#include <stdlib.h>
#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;
}
correctly?
#include <stdio.h>
#include <stdlib.h>
#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;
}