简体   繁体   English

将数组参数传递给函数

[英]Passing array argument to a function

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) ? 为什么将参数b而不是b[]作为sum_array(b[],10)传递?
NOTE : I have no knowledge of pointers. 注意 :我不知道指针。

In C, arrays are passed as a pointer to the first element. 在C语言中,数组作为指向第一个元素的指针传递。 The type of b is array. b类型是数组。

When passing b , you're actually passing a pointer to the first element of the array. 当传递b ,实际上是在传递指向数组第一个元素的指针。

  • why passing the parameter b and not b[] as sum_array(b[],10) 为什么将参数b而不是b []作为sum_array(b [],10)传递

Short answer: Because b[] is invalid syntax. 简短答案:因为b[]是无效的语法。

Here 这里

int b[10];

variable b is declared. 声明了变量b int [10] is type of variable. int [10]是变量的类型。

Since functions accept identifiers as parameters, not types, you should pass identifier to function. 由于函数接受标识符作为参数,而不是类型,因此应将标识符传递给函数。 Identifier is b . 标识符是b

  • NOTE: I have no knowledge of pointers. 注意:我不知道指针。

It has nothing to do with pointers. 它与指针无关。

The function is expecting a pointer to an int array, so you need to pass a pointer to the start of the array. 该函数需要一个指向int数组的指针,因此您需要将一个指针传递给该数组的开头。 b[10] points to the eleventh (!) index of a ten element array. b[10]指向十元素数组的第十一个(!)索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM