When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.
3 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.
Here's the code that I have tried so far: ```#include <stdio.h>
#include <stdlib.h>
int main() {
int row, col;
printf("Please give the second dimension: ");
scanf("%d", &col);
int (*arr)[col] = malloc(5 * sizeof(int[col]));
printf("Please give the numbers: ");
for (row = 0; row < 5; row++) {
for (col = 0; col < (sizeof(*arr) / sizeof(int)); col++) {
scanf("%d", &arr[row][col]);
}
}
printf("The matrix is:\n");
for (row = 0; row < 5; row++) {
for (col = 0; col < (sizeof(*arr) / sizeof(int)); col++) {
printf("%d ", arr[row][col]);
}
printf("\n");
}
printf("\nThe max numbers per row/column are:\n");
for (row = 0; row < 5; row++) {
int row_max = arr[row][0];
for (col = 1; col < (sizeof(*arr) / sizeof(int)); col++) {
if (arr[row][col] > row_max) {
row_max = arr[row][col];
}
}
for (col = 0; col < (sizeof(*arr) / sizeof(int)); col++) {
if (row == 0) {
printf("--");
}
printf("--");
}
if (row == 0) {
printf("-\n");
}
printf("\n");
for (col = 0; col < (sizeof(*arr) / sizeof(int)); col++) {
if (col == 0) {
printf("%d ", arr[row][col]);
} else {
printf("| %d ", arr[row][col]);
}
}
printf("| %d\n", row_max);
}
for (col = 0; col < (sizeof(*arr) / sizeof(int)); col++) {
if (col == 0) {
printf("--");
} else {
printf("---");
}
}
printf("-\n");
for (col = 0; col < (sizeof(*arr) / sizeof(int)); col++) {
int col_max = arr[0][col];
for (row = 1; row < 5; row++) {
if (arr[row][col] > col_max) {
col_max = arr[row][col];
}
}
if (col == 0) {
printf("%d ", col_max);
} else {
printf("| %d ", col_max);
}
}
printf("|\n");
free(arr);
return 0;
}And here's the output that I get::pray: Please give the second dimension: 3
Please give the numbers: 1 8 3 6 2 9 5 9 7 8 2 1 3 5 5
The matrix is:
1 8 3
6 2 9
5 9 7
8 2 1
3 5 5
8 | 9 | 9 |```
I allocate memory for the 2D array of 5 x col size using malloc as said. And I declare arr as a pointer to an array of col integers (int (*arr)[col]), and we allocate 5 such arrays using 5 * sizeof(int[col]). This ensures that only the second dimension of the array is allocated dynamically.