1. 程式人生 > >C++中數組作為形參進行傳遞(轉)

C++中數組作為形參進行傳遞(轉)

傳遞 highlight bsp 是個 也不能 fun 浪費 tor tmp

有兩種傳遞方法,一種是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修改數數組也是一樣,都會修改實參本身!

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

  

C++中數組作為形參進行傳遞(轉)