Declare the functions like
void SetArr( int ( *arr )[100], int n );
void PrintfArr( int ( *arr )[100], int n );
You may not declare the functions as it is shown in the answer that you marked as the best
Consider the following code where instead of 100 I am using 3 for the array dimensions.
If you will print the array in function PrintArr and in main you will get different results!
#include <stdio.h>
void SetArr( size_t n, int (*arr)[n] )
void PrintArr( size_t n, int (*arr)[n] )
int main(void)
{
int arr[3][3];
size_t n = 2;
SetArr( n, arr );
PrintArr( n, arr );
printf( "\n" );
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < n; j++ ) printf( "%2d", arr[i][j] );
printf( "\n" );
}
return 0;
}
void SetArr( size_t n, int (*arr)[n] )
{
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < n; j++ ) arr[i][j] = i * n + j;
}
}
void PrintArr( size_t n, int (*arr)[n] )
{
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < n; j++ ) printf( "%2d", arr[i][j] );
printf( "\n" );
}
}
The program output is
0 1
2 3
0 1
3 1
As you see the first output does not coincide with the second output. You would get the correct result if the functions were declared as I pointed in the beginning of the post. For example
#include <stdio.h>
void SetArr( int (*arr)[3], size_t n );
void PrintArr( int (*arr)[3], size_t n );
int main(void)
{
int arr[3][3];
size_t n = 2;
SetArr( arr, n );
PrintArr( arr, n );
printf( "\n" );
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < n; j++ ) printf( "%2d", arr[i][j] );
printf( "\n" );
}
return 0;
}
void SetArr( int (*arr)[3], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < n; j++ ) arr[i][j] = i * n + j;
}
}
void PrintArr( int (*arr)[3], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
for ( size_t j = 0; j < n; j++ ) printf( "%2d", arr[i][j] );
printf( "\n" );
}
}
The program output is
0 1
2 3
0 1
2 3
As you can see in this case the both outputs coincide.
printf("%d", arr[i][i]);call inPrintArrshould be modified toprintf("%d", arr[i][j]);...int (*arr)[]doesn't specify the size of the array pointed to... so there's no way for the compiler to know how big the rows are in your 2D array inside the functions. If you'd usedint (*arr)[100], it should work... though then your row size is fixed at 100ints.void SetArr(int n, int (*arr)[n])