Passing array argument to a function

旧街凉风 提交于 2019-12-08 10:28:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!