在C語言中,直接在參數中聲明數組變量是無法實現傳值傳參的,這時只會把數組的首地址傳過去。將數組放置到一個struct中進行傳參,可以實現傳值的方式。例如下面的程序:
[cpp]
- #include <stdio.h>
-
- struct tag {int a[100]};
- struct tag orange, lime, lemon;
-
- struct tag twofold(struct tag s){
- int i;
- for(i=0; i<100; i++){
- s.a[i] *= 2;
- }
- return s;
- }
-
- int main(){
- int i;
- for(i=0; i<100; i++){ orange.a[i] = 1; }
- lime = twofold(orange);
- for(i=0; i<10; i++){
- printf("before: lime.a[%d] = %d\n", i, lime.a[i]);
- }
- lemon = lime;
- for(i=0; i<100; i++){ lemon.a[i] = 7; }
-
- for(i=0; i<10; i++){
- printf("lemon.a[%d] = %d\n", i, lemon.a[i]);
- }
-
- for(i=0; i<10; i++){
- printf("after: lime.a[%d] = %d\n", i, lime.a[i]);
- }
- }
輸出結果:
[java]
- before: lime.a[0] = 2
- before: lime.a[1] = 2
- before: lime.a[2] = 2
- before: lime.a[3] = 2
- before: lime.a[4] = 2
- before: lime.a[5] = 2
- before: lime.a[6] = 2
- before: lime.a[7] = 2
- before: lime.a[8] = 2
- before: lime.a[9] = 2
- lemon.a[0] = 7
- lemon.a[1] = 7
- lemon.a[2] = 7
- lemon.a[3] = 7
- lemon.a[4] = 7
- lemon.a[5] = 7
- lemon.a[6] = 7
- lemon.a[7] = 7
- lemon.a[8] = 7
- lemon.a[9] = 7
- after: lime.a[0] = 2
- after: lime.a[1] = 2
- after: lime.a[2] = 2
- after: lime.a[3] = 2
- after: lime.a[4] = 2
- after: lime.a[5] = 2
- after: lime.a[6] = 2
- after: lime.a[7] = 2
- after: lime.a[8] = 2
- after: lime.a[9] = 2