[英]warning: passing argument 2 of ‘accept’ from incompatible pointer type [-Wincompatible-pointer-types]
[英]warning: passing argument 1 of 'display' from incompatible pointer type [-Wincompatible-pointer-types]
#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");
}
}
对于上面的代码,我得到的结果低于 output,而且我是初学者,因此无法理解和解决问题。 请让我明白这里的问题是什么。
在这次通话中
display(arr, 2, 2);
二维数组arr
声明为
int arr[2][2], i, j;
隐式转换为指向其类型为int ( * )[2]
的第一个元素的指针。 然而对应的 function 参数的类型是int *
并且这些指针类型之间没有隐式转换。
您至少需要声明第一个 function 参数,例如
int ptr_Arr[][2]
或者
int ( *ptr_Arr )[2]
在 function 内的嵌套 for 循环中使用指针,可以通过以下方式声明和定义 function
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");
}
}
并称呼
display( arr, sizeof( arr ) / sizeof( *arr ) );
如果想把function写成各种大小的二维arrays那么function可以通过如下方式声明和定义(前提是编译器支持变长数组)
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");
}
}
并称为例如
display( 2, 2, arr );
最后,您可以将二维数组重新解释为 function 中的一维数组。在这种情况下,您需要隐式转换指针。 例如
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");
}
}
function 被称为
display( ( int * )arr, 2, 2 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.