C++中數組作爲形參的方法

原鏈接:https://www.cnblogs.com/abella/p/10607061.html

有兩種傳遞方法,一種是function(int a[]); 另一種是function(int *a)

這兩種兩種方法在函數中對數組參數的修改都會影響到實參本身的值!

對於第一種,根據之前所學,形參是實參的一份拷貝,是局部變量。但是數組是個例外,因爲數組的數據太多了,將其一一賦值既麻煩又浪費空間,所以數組作爲參數傳遞給函數的只是數組首元素的地址,數據還是在內存裏的,函數在需要用到後面元素時再按照這個地址和數組下標去內存查找。也就是說後面的元素根本沒到函數裏來。所以,這裏也不能在test()函數內部用sizeof求數組的大小,必須在外面算好了再傳進來。

對於第二種,則是傳址調用,無需再說。

這裏還有幾點需要注意:

1.在以上兩個函數的形參前面加上const則表示整個數組只讀,而不是隻有首地址對應存儲的數據只讀。

2.第二種形式不能用C++11中的for...auto來循環打印。

3.數組的大小要用sizeof()來求,不能用.size(),因爲.size()只有struct 或者union才能用, vector算是struct!

4.如果在函數內部又聲明一個int* tmp類型的變量,然後把p賦值給tmp, 通過tmp修改數數組也是一樣,都會修改實參本身!

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

#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");

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章