问题
On calling the function
int sum_array(int array[], int arr_length)
{
int sum = 0;
while(--arr_length >= 0)
sum += array[arr_length];
return sum;
}
in main function
int main()
{
int b[10];
...
total = sum_array(b,10);
...
}
why passing the argument b
, not b[]
as sum_array(b[],10)
?
NOTE: I have no knowledge of pointers.
回答1:
In C, arrays are passed as a pointer to the first element. The type of b
is array.
When passing b
, you're actually passing a pointer to the first element of the array.
回答2:
- why passing the parameter b and not b[] as sum_array(b[],10)
Short answer: Because b[]
is invalid syntax.
Here
int b[10];
variable b
is declared. int [10]
is type of variable.
Since functions accept identifiers as parameters, not types, you should pass identifier to function. Identifier is b
.
- NOTE: I have no knowledge of pointers.
It has nothing to do with pointers.
回答3:
The function is expecting a pointer to an int array, so you need to pass a pointer to the start of the array. b[10]
points to the eleventh (!) index of a ten element array.
来源:https://stackoverflow.com/questions/17353055/passing-array-argument-to-a-function