C语言中使用struct实现数组复制
在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
相关推荐
IT之家 2020-03-11
graseed 2020-10-28
zbkyumlei 2020-10-12
SXIAOYI 2020-09-16
jinhao 2020-09-07
impress 2020-08-26
liuqipao 2020-07-07
淡风wisdon大大 2020-06-06
yoohsummer 2020-06-01
chenjia00 2020-05-29
baike 2020-05-19
扭来不叫牛奶 2020-05-08
hxmilyy 2020-05-11
黎豆子 2020-05-07
xiongweiwei00 2020-04-29
Cypress 2020-04-25
冰蝶 2020-04-20