Why does C use array parameters as pointers for programming? array/pointer arguments
#include
void print_array_test(char ca[]){ printf("ca : %s\n",ca); printf("&ca : %s\n",&ca); printf("&(ca[0]) : %s\n",&(ca[0])); printf("&(ca[1]) : %s\n",&(ca[1])); printf("*(ca+0) : %c\n",*(ca+0)); printf("*(ca+1) : %c\n",*(ca+1)); printf("ca+1 : %s\n",ca+1);}void print_ptr_test(char *pa){ printf("pa : %s\n",pa); printf("&pa : %s\n",&pa); printf("&(pa[0]) : %s\n",&(pa[0])); printf("&(pa[1]) : %s\n",&(pa[1])); printf("pa+1 : %s\n",pa+1); printf("pa[1] : %c\n",pa[1]); printf("*(pa+1) : %c\n",*(pa+1)); printf("++pa : %s\n",++pa);}int main(){ char abc[]="hello,world!"; print_array_test(abc); print_ptr_test(abc); return 0;}
Array abc [20] = "hello, world! "
And abc [I] have the same meaning as abc + I -- the address of abc [I] is used.
Pointer pa = abc;
Pa [I] is equivalent to * (pa + I) -- the value of abc [I] is used.
In view of the above program, run:
[Root @ localhost code] #./arrayandptr
Ca: hello, world!
& Ca :???,??;
& (Ca [0]): hello, world!
& (Ca [1]): ello, world!
* (Ca + 0): h
* (Ca + 1): e
Ca + 1: ello, world!
Pa: hello, world!
& Pa :???,??;
& (Pa [0]): hello, world!
& (Pa [1]): ello, world!
Pa + 1: ello, world!
Pa [1]: e
* (Pa + 1): e
++ Pa: ello, world!
[Root @ localhost code] #