在C语言中,直接在参数中声明数组变量是无法实现传值传参的,这时只会把数组的首地址传过去。将数组放置到一个struct中进行传参,可以实现传值的方式。例如下面的程序:
#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]); } }
输出结果:
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
参考《C专家编程》