C语言 中多维数组的调用 与 指针位置

c中多维数组的指针形式:
对于int a[4][5];a为数组指针,其类型为 int (*p)[5];后面的[5]不可省略;在参数调用时也需要声明为func(int (*p)[5]);不能使用int ** 。
例如:
void func(char (*p)[5]) {//或者char p[][5]
p[2][3]='9';//这里可以使用p[i][j]
}
int main() {
char a[4][5]={0};
func(a);
return 0;
}
若将调用形式改成下面的形式,编译器不会报错,但执行将出错
/*
以sizeof(int *)=8 为例
void func(char **p) {
p[2][3]='9';//p为int**,则p+2*sizeof(char *)实际值是a[3][1]的地址;*(p+2)的值为a[3][1],
//则(*(p+2))+3 为a[3][1]+3*sizeof(char);
//进而*((*(p+2))+3)为*(a[3][1]+3*sizeof(char)),不是我们想要的值
}
*/
实测例子:
/*
void exist(int **board, int boardRowSize, int boardColSize) {
if(NULL==board || 0==boardRowSize || 0==boardColSize)
return ;
printf(" * size is %d \n",sizeof(char *)); // 结果: * size is 8
printf("the val is 0x%x \n",board); // the val is 0x588b1920
printf("the val is 0x%x \n",board+1); // the val is 0x588b1928
printf("the val is 0x%lx %c \n",board[0],board[0]); // the val is 0x6300000061 a
printf("the val is 0x%lx %c \n",board[0]+1,board[0]+1);// the val is 0x6300000065 e
printf("the val is 0x%lx %c \n",board[1],board[1]); // the val is 0x6700000065 e
printf("the val is 0x%lx %c \n",board[1]+1,board[1]+1);// the val is 0x6700000069 i
//printf("the val is %x \n",*board[0]);//加入此句出错: load of misaligned address //0x006300000061 for type 'int', which requires 4 byte alignment,
/*即使把c[0][0]改成sizeof(int)的倍数,也会执行出错,具体要看其地址值是否在当前计算机的进程可用地址空间中*/
return ;
}
int main(int argc,char **argv )
{
int c[3][3]={'a','c','e','g','i','k','m','o','q'};//0x61 0x63 0x65 0x67 0x69 0x6A 0x6C 0x6E 0x71
exist(c,3,3);
printf("end \n");
return 0;
}
*/
若将数组类型改成 char c[3][3];函数调用改为 exist(char **board, int boardRowSize, int boardColSize)
结果如下:
* size is 8 the val is 0xdaeadc10 the val is 0xdaeadc18 the val is 0x6f6d6b6967656361 a the val is 0x6f6d6b6967656362 b the val is 0x71 q //取决于实际在栈中的位置附近的数值情况the val is 0x72 r //end
*****************************************************************************************************************************
注意:
在leetcode中常见到的function(char * *board, int boardRowSize, int boardColSize)是建立了指针数组后的调用,其实际形式如下:
/*
bool exist(char * *board, int boardRowSize, int boardColSize) {
if(NULL==board || 0==boardRowSize || 0==boardColSize)
return false;
for(int i=0;i<boardRowSize;i++)
for(int j=0;j<boardColSize;j++)
{
printf("the %d %d val is %c \n",i,j,board[i][j]);//这里使用board[][]是因为
// *(board+i)存在确定的存储空间,进而可以*(*(board+i)+j)
}
return false;
}
int main(int argc,char **argv )
{
char a1[3]={'a','c','d'};
char a2[3]={'d','e','f'};
char a3[3]={'g','h','i'};
char * c[3]={a1,a2,a3};
bool t=false;
t=exist(c,3,3);
printf("bool is %d",t);
return 0;
}
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值