gpt4 book ai didi

c - 如何引用二维数组?

转载 作者:太空宇宙 更新时间:2023-11-04 00:24:24 25 4
gpt4 key购买 nike

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

#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;
}

当我尝试编译时得到以下消息:

 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])
^

当我运行上面的代码时,出现段错误。

最佳答案

函数参数被声明为类型int *

void display(int *s)

虽然作为参数传递给函数的原始数组具有类型

int [3][4]

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

int ( * )[4]

如您所见,int *int ( * )[4] 是两种不同的类型,并且没有从一种类型到另一种类型的隐式转换。

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

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

display( ( int * )s );

你要的是下面的

#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;
}

程序输出可能如下所示

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

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

void display( int ( *a )[4], size_t m );

关于c - 如何引用二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30816882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com