函数形参为数组或指针小测试,你能猜对答案吗?
两个问题:
1、下面两个函数my_array_func和my_pointer_func第一个输出结果是否一样?(P6和P17)
2、每个函数的第一个输出和第二个输出结果是否一样?(P6与P7,,,P17与P18)
能猜对的,估计也都理解C里面数组和指针的区别于联系。感觉自己不是很理解的,建议看C专家编程P84的图。
代码如下:
1 char ga[] = "abcdefghijklm"; 2 3 void 4 my_array_func(char ca[10]) 5 { 6 printf("addr of array param = %#x\n", &ca); 7 printf("the element of ca = %#x\n", ca); 8 printf("addr (ca[0]) = %#x\n", &(ca[0])); 9 printf("addr (ca[1]) = %#x\n", &(ca[1])); 10 printf("++ca = %#x\n\n", ++ca); 11 } 12 13 14 void 15 my_pointer_func(char *pa) 16 { 17 printf("addr of ptr param = %#x\n", &pa); 18 printf("the element of pa = %#x\n", pa); 19 printf("addr (pa[0]) = %#x\n", &(pa[0])); 20 printf("addr (pa[1]) = %#x\n", &(pa[1])); 21 printf("++pa = %#x\n\n", ++pa); 22 } 23 24 int 25 main() 26 { 27 printf("addr of global array = %#x\n", &ga); 28 printf("addr (ga[0]) = %#x\n", &(ga[0])); 29 printf("addr (ga[1]) = %#x\n\n", &(ga[1])); 30 31 my_array_func(ga); 32 my_pointer_func(ga); 33 34 return 0; 35 }
答案
C:\Program Files\Microsoft Visual Studio 10.0\VC>array.exe addr of global array = 0x8bb000 addr (ga[0]) = 0x8bb000 addr (ga[1]) = 0x8bb001 addr of array param = 0x22f9d8 the element of ca = 0x8bb000 addr (ca[0]) = 0x8bb000 addr (ca[1]) = 0x8bb001 ++ca = 0x8bb001 addr of ptr param = 0x22f9d8 the element of pa = 0x8bb000 addr (pa[0]) = 0x8bb000 addr (pa[1]) = 0x8bb001 ++pa = 0x8bb001