可能重复:
我们何时需要将数组大小作为参数传递
所以我刚开始使用数组,我需要创建3个函数来让我学习.
int sumarray(int a[], int n);
// a is an array of n elements
// sumarray must return the sum of the elements
// you may assume the result is in the range
// [-2^-31, 2^31-1]
int maxarraypos(int a[], int n);
// a is an array of n elements
// maxarraypos must return the position of
// the first occurrence of the maximum
// value in a
// if there is no such value, must return 0
bool lexlt(int a[], int n, int b[], int m);
// lexicographic "less than" between an array
// a of length n and an array b of length m
// returns true if a comes before b in
// lexicographic order; false otherwise
Run Code Online (Sandbox Code Playgroud)
我究竟如何创建这些功能?
因为sumarray,我很困惑,因为数组存储了一定长度的东西.为什么需要第二个参数n?
还有我如何测试消耗数组的函数?我在想sumarray([3], 3)......是吗?
Ric*_*III 10
传递给函数时,数组衰减成指针,指针本身不存储长度.第二个参数将存储数组中元素的数量,因此,它看起来像这样:
int values[] = { 16, 13, 78, 14, 91 };
int count = sizeof(values) / sizeof(*values);
printf("sum of values: %i\n", sumarray(values, count));
printf("maximum position: %i\n", maxarraypos(values, count));
Run Code Online (Sandbox Code Playgroud)