I am reading the TCPL by K&R, when I read something about array and pointer, I write this small code below:
#include <stdio.h>
int sum(int a[])
{
int t = 0;
int length = sizeof(a) / sizeof(a[0]) ;
// printf("%d\n",length);
for(int i = 0; i != length; ++i)
{
t += a[i];
}
return t;
}
int main()
{
int b[5] = {1, 2, 3, 4, 5};
printf("%d\n",sum(b));
return 0;
}
The output answer is 1 NOT 15, then I debug this code by adding printf("%d\n",length);
the output length is 1 NOT 5.
The TCPL tells that a array name converts to pointer when the array name used as argument, but the output answer is wrong, so I wonder that:
- What happend when call a funcion with array name used as argument?
- The array
a[]
used parameter insum(int a[])
has storage or not? - I see two styles when calling a array :
fun(int a[]); fun(b)
andfun(int *a);fun(b)
,what the difference?
Thx very much :-)