L
lovecreatesbea...
This code snippet is an exercise on allocating two dimension array
dynamically. Though this one is trivial, is it a correct one?
Furthermore, when I tried to make these changes to the original
example:
for (i = 0; i < ROW + 2; ++i){ /*line 14*/
strcpy(array, "C! C!"); /*line 15*/
Apparently, the modified code wrote to the memory unit outside the
allocated array, but the program ran well and there was no Segmentation
fault. Thank you.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define ROW 4
#define COL 3
int main(void){
char (*array)[COL];
int i;
array = malloc(ROW * sizeof *array);
if (array){
for (i = 0; i < ROW; ++i){ /*line 14*/
strcpy(array, "C!"); /*line 15*/
printf("%s\n", array);
}
}
free(array);
return 0;
}
dynamically. Though this one is trivial, is it a correct one?
Furthermore, when I tried to make these changes to the original
example:
for (i = 0; i < ROW + 2; ++i){ /*line 14*/
strcpy(array, "C! C!"); /*line 15*/
Apparently, the modified code wrote to the memory unit outside the
allocated array, but the program ran well and there was no Segmentation
fault. Thank you.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define ROW 4
#define COL 3
int main(void){
char (*array)[COL];
int i;
array = malloc(ROW * sizeof *array);
if (array){
for (i = 0; i < ROW; ++i){ /*line 14*/
strcpy(array, "C!"); /*line 15*/
printf("%s\n", array);
}
}
free(array);
return 0;
}