#include<stdio.h>
/* create a 2D array by taking input from the user and write a display function to display the contents
of this array*/
void display(int *ptr_Arr, int x, int y);
int main(){
int arr[2][2], i, j;
for(i=0; i<=1; i++){
for(j=0; j<=1; j++){
printf("Enter the value of element %dX%d: ", i, j);
scanf("%d", &arr[i][j]);
}
}
display(arr, 2, 2);
return 0;
}
void display(int *ptr_Arr, int a, int b){
int x, y;
for(x=0; x<a; x++){
for(y=0; y<b; y++){
printf("%d ", *ptr_Arr);
ptr_Arr++;
}
printf("\n");
}
}
I get below output for the above code and I am not able to understand and resolve the problem as I am a beginner. Please make me understand what the problem here is.
In this call
display(arr, 2, 2);
the two-dimensional array arr
declared like
int arr[2][2], i, j;
is implicitly converted to a pointer to its first element of the type int ( * )[2]
. However the corresponding function parameter has the type int *
and there is no implicit conversion between these pointer types.
You need at least declare the first function parameter like
int ptr_Arr[][2]
or
int ( *ptr_Arr )[2]
Using pointers in the nested for loops within the function the function can be declared and defined for example the following way
void display( int ptr_Arr[][2], size_t a )
{
for( int ( *p )[2] = ptr_Arr; p != ptr_Arr + a; ++p )
{
for ( int *q = *p; q != *p + sizeof( *p ) / sizeof( **p ); ++q )
{
printf("%d ", *q);
}
printf("\n");
}
}
and called like
display( arr, sizeof( arr ) / sizeof( *arr ) );
If you want to write the function for two-dimensional arrays with various sizes then the function can be declared and defined the following way (provided that the compiler supports variable length arrays)
void display( size_t a, size_t b, int ptr_Arr[][b] )
{
for( int ( *p )[b] = ptr_Arr; p != ptr_Arr + a; ++p )
{
for ( int *q = *p; q != *p + b; ++q )
{
printf("%d ", *q);
}
printf("\n");
}
}
and called like for example
display( 2, 2, arr );
And at last you could reinterpret the two-dimensional array as a one-dimensional array within the function. In this case you will need implicitly to cast pointers. For example
void display( int *ptr_Arr, size_t a, size_t b )
{
for ( int *p = ptr_Arr; p != ptr_Arr + a * b; p += b )
{
for ( int *q = *p; q != p + b; ++q )
{
printf("%d ", *q);
}
printf("\n");
}
}
And the function is called like
display( ( int * )arr, 2, 2 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.