如何引用二维数组?

use*_*777 1 c arrays pointers

我知道二维数组作为一维数组存储在内存中.因此,遵循相同的逻辑,我试图通过引用使用单个指针传递数组,就像对一维数组所做的那样.以下是我的代码:

#include<stdio.h>
void display(int *s)
{
    int i,j;
    for(i=0;i<3;i++)
    {
        for(j=0;j<4;j++)
        {
            printf("%d ",s[i][j]);
        }
        printf("\n");
    }
}
int main()
{
    int s[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
    printf("address of the array is %p\n",s);
    printf("value is %p\n",*s);
    int i;
    printf("address of the repective array is\n");
    for(i=0;i<3;i++)
    {
        printf("address of the array is %p\n",s[i]);
    }
    display(s);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译此获取以下消息时:

 twodarray.c: In function ‘main’:
twodarray.c:25:2: warning: passing argument 1 of ‘display’ from    incompatible pointer type [enabled by default]
  display(s);
  ^
twodarray.c:2:6: note: expected ‘int **’ but argument is of type ‘int (*)[4]’
 void display(int *s[3])
      ^
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,我得到分段错误错误.

Vla*_*cow 6

函数参数声明为具有类型 int *

void display(int *s)
Run Code Online (Sandbox Code Playgroud)

而原始数组传递给函数,因为参数有类型

int [3][4]
Run Code Online (Sandbox Code Playgroud)

它被隐式转换为指向其第一个具有类型的元素的指针

int ( * )[4]
Run Code Online (Sandbox Code Playgroud)

正如您所看到的那样int *,int ( * )[4]它们是两种不同的类型,并且没有从一种类型到另一种类型的隐式转换.

此外,由于函数参数具有类型,因此int *您可能无法在函数表达式中写入s[i][j].因为如果要将下标运算符应用于此指针,例如,s[i]则此表达式是类型的标量对象int.它不是指针.所以你可能不会第二次应用下标运算符.

您必须将参数显式转换为函数调用中的参数类型.例如

display( ( int * )s );
Run Code Online (Sandbox Code Playgroud)

你想要的是以下内容

#include <stdio.h>

void display( int *a, size_t m, size_t n )
{
    for ( size_t i = 0; i < m; i++ )
    {
        for ( size_t j = 0; j < n; j++ )
        {
            printf( "%2d ", a[i * n + j] );
        }
        printf( "\n" );
    }
}

int main( void )
{
    int a[3][4] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };

    printf( "The address of the array is %p\n", ( void * )a );

    printf( "The address of the first row is %p\n", ( void * )*a );

    printf("The address of the respective array rows are\n");
    for ( size_t i = 0; i < 3; i++ )
    {
        printf( "address of row %zu is %p\n", i, ( void * )a[i] );
    }

    display( ( int * )a, 3, 4 );

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

程序输出可能看起来如下

The address of the array is 0xbf85d2dc
The address of the first row is 0xbf85d2dc
The address of the respective array rows are
address of row 0 is 0xbf85d2dc
address of row 1 is 0xbf85d2ec
address of row 2 is 0xbf85d2fc
 1  2  3  4 
 5  6  7  8 
 9 10 11 12 
Run Code Online (Sandbox Code Playgroud)

虽然以下面的方式声明函数会更好,以避免不必要的转换和复杂的函数实现

void display( int ( *a )[4], size_t m );
Run Code Online (Sandbox Code Playgroud)