C++函数传递数组的两种方式

数组与指针。

传首地址过去,然后通过地址输出数组元素。

1、一维数组

#include<iostream>
using namespace std;
#include <cstring>
void farray1(int array1[],int len)//注:此处是无法通过array1得到长度的,只能通过传参,因为其是数组首地址。
{
    for(int i=0;i<len;i++)
    {
        //cout<<array1[i]<<endl;
        cout<<*(array1+i)<<endl;//因为传的是首地址,所以这两种方法都可以输出数组元素
    }
}

void farray2(int *array1,int len)//注:此处是无法通过array1得到长度的,只能通过传参,因为其是数组首地址。
{
    for(int i=0;i<len;i++)
    {
        //cout<<array1[i]<<endl;
        cout<<*(array1+i)<<endl;//因为传的是首地址,所以这两种方法都可以输出数组元素

    }
}
void main()
{
  int marks[5] = {40, 90, 73, 81, 35};
  int length1=sizeof(marks)/4;
  farray1(marks,length1);
  farray2(marks,length1);
  system("pause");
}

2、二维数组:

#include<iostream>
using namespace std;
#include <cstring>
void farray1(int array1[][3],int len1,int len2)//注:此处是无法通过array1得到长度的,只能通过传参,因为其是数组首地址。
{
    for(int i=0;i<len1;i++)
    {
        for(int j=0;j<len2;j++)
        //cout<<array1[i][j]<<endl;
        cout<<*(*(array1+i)+j)<<endl;//因为传的是首地址,所以这两种方法都可以输出数组元素
    }
}

void farray2(int (*array1)[3],int len1,int len2)//注:要写明数组列数,不然无法传递
{
    for(int i=0;i<len1;i++)
    {
        for(int j=0;j<len2;j++)
        //cout<<array1[i][j]<<endl;
        cout<<*(*(array1+i)+j)<<endl;//因为传的是首地址,所以这两种方法都可以输出数组元素
    }
}
void main()
{
    int marks[2][3] = {{40, 90, 73},{ 81, 35, 56}};
  int length1=sizeof(marks)/4;//获得数组总长度
  int length2=sizeof(marks[0])/4;//获得列数
  int length3=length1/length2;//获得行数
  farray1(marks,length3,length2);
  farray2(marks,length3,length2);
  system("pause");
}
step by step.
原文地址:https://www.cnblogs.com/answer727/p/6965345.html