数组做函数形参

将数组作为参数传递

有两种传递方法,一种是 f(int a[]),另一种是f(int *a)

这两种方法在函数中对数组参数的修改都会影响到实参本身的值!

不允许拷贝数组以及使用数组时通常会将其转换成指针。因为不能拷贝数组,所以我们无法以值传递的方式使用数组参数。因为数组会被转换成指针,所以当我们为函数传递一个数组时,实际上传递的是指向数组首元素的指针。

f(int a[10])也是一种方法,这里的维度表示我们期望数组含有多少元素,实际不一定

eg:

#include <stdio.h>
#include <algorithm>
using namespace std;
 
void test1(int[], int size);
void test2(int *p, int size);
//void test2(const int *p, int size);
 
int main(void)
{
    int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int size = sizeof(a)/sizeof(int);
    /*这里打印出的a值与test1(),test2()中的p值相等
     *即地址值相同*/
    printf("%p \n", a);
    //test1(a, size);
    test2(a, size);
    int i;
    printf("main: ");
    for(i = 0; i < size; ++i)
    {
        printf("%d ", a[i]);
    }
}
 
void test1(int p[], int size)
{
    printf("%p \n", p);
    p[4] = 111;
    printf("test1: ");
    int i;
    for(i = 0; i < size; ++i)
    {
        printf("%d ", p[i]);
    }
    printf("\n");
}
 
void test2(int *p, int size)
{
    printf("%p \n", p);
    *(p+4) = 222;
    printf("test2: ");
    int i;
    for(i = 0; i < size; ++i)
    {
        printf("%d ", *(p+i));
    }
    printf("\n");
}

数组形参误区

#include<iostream>
using namespace std;
int num(int *a)
{
    cout<<sizeof(a)/sizeof(*a)<<endl;
    cout<<sizeof(a)<<endl;//指针所占用空间大小
    cout<<sizeof(*a)<<endl;//指针所指向元素所占空间大小
    cout<<sizeof(int)<<endl;
    return 0;
}
int main()
{
    int a[]={0,1,3,4,5,56};
    cout<<sizeof(a)/sizeof(*a)<<endl;
    num(a);
    return 0;
}

输出

jietu20181214-135505@2x.jpg
原因:实际上传递的是指向数组首元素的指针的副本

猜你喜欢

转载自blog.csdn.net/weixin_43425693/article/details/90018949