函数传参
1 函数传参的顺序:
#include <stdio.h>
//进栈栈地址是递减的。先进栈的在高地址,后进栈的在低地址。
//函数传参:参数从最右边先进栈,先进后出。
#include <stdio.h> void fun(int a, ...) { int i; int *temp = &a; temp++; for (i = 0; i < a; ++i) { printf("%d\n" , *temp); temp++; } } void funstr(int a, ...) { int i; int *temp = &a; temp++; for (i = 0; i < a; ++i) { printf("%s" , (char*)(*temp)); temp++; } printf("\n"); } int main() { int a = 12; int b = 22; int c = 32; int d = 42; fun(4, a, b, c, d); char *as = "I "; char *bs = "am " ; char *cs = "fire!" ; funstr(3 , as ,bs,cs); return 0; } /* gcc for.c ;./a.out 12 22 32 42 I am fire! */
2 拷贝传递
typedef struct { char a; char b ; }ST; int fun2(ST st){ printf("in fun2 : 0x%x\n",&(st.a)); printf("in fun2 : 0x%x\n",&(st.b)); } int main() { ST st ; printf("0x%x\n",&(st.a)); printf("0x%x\n",&(st.b)); fun2( st); }
/*
0xbfc2841e
0xbfc2841f
in fun2 : 0xbfc28400 //在函数内外的st内容相等,地址改变(值传递,拷贝传递)。占据堆栈中sizeof(ST)的内存。
in fun2 : 0xbfc28401
*/