Originally Posted by
vxs8122
So there is absolutely no way to resize the double_digit array while keeping all the data?
If you want to resize an array, the normal way is to use dynamic memory. This adds complexity. Here is an example:
Code:
#define ROWS 2
int **make_array2d(int cols) {
int **arr = realloc(NULL, sizeof(int) * ROWS);
for (int i=0; i < ROWS; i++) {
arr[i] = realloc(NULL, sizeof(int) * cols);
}
return arr;
}
int **grow_array2d(int **arr, int cols) {
arr = realloc(arr, sizeof(int) * ROWS);
for (int i=0; i < ROWS; i++) {
arr[i] = realloc(arr[i], sizeof(int) * cols);
}
return arr;
}
int main(void)
{
// make array 2x2
int **double_digit = make_array2d(2);
double_digit[0][0] = 11;
double_digit[0][1] = 12;
// resize array to 2x4
double_digit = grow_array2d(double_digit,4);
double_digit[0][2] = 13;
double_digit[0][3] = 14;
double_digit[1][0] = 21;
double_digit[1][1] = 22;
double_digit[1][2] = 23;
double_digit[1][3] = 24;
// print result
for (int i=0; i < 2; i++) {
for (int j=0; j < 4; j++) {
printf("%4d", double_digit[i][j]);
}
printf("\n");
}
return EXIT_SUCCESS;
}
Note there is no error checking, which normally should be used. And the number of rows is fixed. To make it unfixed you would need to have a way to track the old number of rows and the new number of rows, and grow_array2d should act accordingly.