The expressions like &mat[i][j]
or mat[i][j]
used in the for loops and the expression mat
used in the statement that allocates memory for an array of pointers
mat = (int **)malloc(*m * sizeof(int *));
for(int i = 0; i < *m; i++)
mat[i] = (int *)malloc(*n * sizeof(int));
for(int i = 0; i < *m; i++)
for(int j = 0; j < *n; j++)
scanf("%d", &mat[i][j]);
for(int i = 0; i < *m; i++)
for(int j = 0; j < *n; j++) {
printf("%d ", mat[i][j]);
printf('\n');
}
are incorect.
Instead you have to write
*mat = (int **)malloc(*m * sizeof(int *));
for(int i = 0; i < *m; i++)
( * mat )[i] = (int *)malloc(*n * sizeof(int));
for(int i = 0; i < *m; i++)
for(int j = 0; j < *n; j++)
scanf("%d", &( *mat )[i][j]);
for(int i = 0; i < *m; i++)
{
for(int j = 0; j < *n; j++) {
printf("%d ", ( *mat )[i][j]);
}
printf( "\n" );
}
That is the parameter mat
has the type int ***
. This means that the original pointer of the type int **
is passed to the function by reference indirectly through a pointer to it. Thus you need to dereference the parameter to get an access to the original pointer.
And this call of printf
printf('\n');
where you are incorrectly using the integer character constant '\n'
instead of the string literal "\n"
should be placed after the inner for loop.
Also there is no sense to declare m
and n
as pointers. The function could be declared at least like
void alloc_matrix(int ***mat, int m, int n) {
Here is a demonstration program
#include <stdio.h>
#include <stdlib.h>
void alloc_matrix( int ***mat, int m, int n )
{
*mat = ( int ** )malloc( m * sizeof( int * ) );
for (int i = 0; i < m; i++)
( * mat )[i] = ( int * )malloc( n * sizeof( int ) );
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
scanf( "%d", &( *mat )[i][j] );
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++) {
printf( "%d ", ( *mat )[i][j] );
}
putchar( '\n' );
}
}
int main( void )
{
enum { M = 2, N = 3 };
int **mat = NULL;
alloc_matrix( &mat, M, N );
for (int i = 0; i < M; i++)
{
free( mat[i] );
}
free( mat );
}
Its output might look like
1 2 3
4 5 6
1 2 3
4 5 6
The first two lines is the user input and the next two lines is the output of elements of the dynamically allocated arrays.