二维数组作为形参的传递

代码实例:

#include<iostream>
#include<cstdio>
#include<map>
using namespace std;

void func1(int arr[][5])//传递数组,需生命数组第二维的大小
{
    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++)cout<<arr[i][j]<<" ";
        cout<<endl;
    }
}
void func2(int (*arr)[5])//传递数组指针,仍需生命第二维的大小
{
    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++)cout<<arr[i][j]<<" ";
        cout<<endl;
    }
}
void func3(int *arr)//传递指针,指针指向首元素即可,但维数组的形状需用其他参数来证明
                    //传参时需要强制转换类型
{
    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++)cout<<*(arr+i*5+j)<<" ";
        cout<<endl;
    }
}
int main()
{
    int arr[5][5];
    int ins=0;
    for(int i=0;i<5;i++){
        for(int j=0;j<5;j++){
            arr[i][j]=++ins;
        }
    }
    func1(arr);
    func2(arr);
    func3((int *)arr);
    return 0;
}

错误示范:

#include <stdio.h>
#include <string.h>
#include <iostream>
using  namespace std; 


int test(int  *a[3]);
int main(int argc, char **argv)
{
    int b[2][3]; 
    test(b);   
	return 0;
}
int test(int *a[3])
{
	int i=0;
  	cout << a[i];
  }

错误原因:

   [Error] cannot convert 'int (*)[3]' to 'int**' for argument '1' to 'int test(int**)'

 大概就是类型不匹配,int (*)[3]不匹配int** 。

赋值的时候可以这么传递,但是传参不可以这样传。

原因:

  修改方式(多种修改方式):

#include <stdio.h>
#include <string.h>
#include <iostream>
using  namespace std; 


int test(int  (*a)[3]);
int main(int argc, char **argv)
{
    int b[2][3]; 
    test(b);   
	return 0;
}
int test(int (*a)[3])
{
	int i=0;
  	cout << a[i];
  }

 

 

 

 

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值