Firstly, in this segment:
int *col_num, *row_num, **matrix;
printf("Enter your column number:\n");
scanf("%d", &col_num);
printf("Enter your row number:\n");
scanf("%d", &row_num);
col_num
and row_num
shouldn't be pointers, and you could just do this instead:
int col_num, row_num, **matrix;
printf("Enter your column number:\n");
scanf("%d", &col_num);
printf("Enter your row number:\n");
scanf("%d", &row_num);
Furthermore, checking the return value of scanf()
is not a bad idea either, just in case the user enters some rubbish.
You also seem to write things like matrix[*row_num] = .........
alot in your program, which is just unnecessary. You shouldn't have to reference *row_num
and *col_num
anywhere. Instead just call row_num
and col_num
by themselves, and that should be fine.
If you want to use **matrix
, which is hard to use at first, you need to use malloc
carefully to accomplish this. Please also see Should I cast the return value of malloc.
First start by:
Allocating memory for the rows:
int **matrix = malloc(row_num * sizeof(*matrix)); /* check return value */
Then for each row, malloc()
some memory for the columns:
for (i = 0; i < row_num; i++) {
matrix[i] = malloc(col_num * sizeof(*matrix[i])); /* check return value */
Then free
the pointers at the end:
free(matrix[i]);
free(matrix);
After using these ideas, your code should look something like this(unless I have misunderstood the purpose of your code):
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[]) {
int row_num, col_num, **matrix;
int i, j;
printf("Enter your column number: ");
if (scanf("%d", &col_num) != 1) {
printf("Invalid input\n");
exit(EXIT_FAILURE);
}
printf("Enter your row number: ");
if (scanf("%d", &row_num) != 1) {
printf("Invalid input\n");
exit(EXIT_FAILURE);
}
matrix = malloc(row_num * sizeof(*matrix)); /* Or sizeof(int *) */
if (!matrix) {
printf("Cannot allocate memory for pointer.\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < row_num; i++) {
matrix[i] = malloc(col_num * sizeof(*matrix[i])); /* Or sizeof(int) */
if (!matrix[i]) {
printf("Cannot allocate memory for pointer.\n");
exit(EXIT_FAILURE);
}
for (j = 0; j < col_num; j++) {
printf("Please Enter %d%d matrix: ",i+1,j+1);
if (scanf("%d", &matrix[i][j]) != 1) {
printf("Invalid input\n");
exit(EXIT_FAILURE);
}
}
}
printf("Your 2D array:\n");
for (i = 0; i < row_num; i++) {
for (j = 0; j < col_num; j++) {
printf("%d ", matrix[i][j]);
}
free(matrix[i]);
matrix[i] = NULL;
printf("\n");
}
free(matrix);
matrix = NULL;
return 0;
}