c - 数组简介

标签 c arrays

<分区>

Possible Duplicate:
when do we need to pass the size of array as a parameter

所以我刚开始使用数组,我需要创建 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

我将如何创建这些函数?

对于 sumarray,我很困惑,因为数组存储的内容在一定长度内。为什么需要第二个参数 n

还有我如何测试一个使用数组的函数?我在想 sumarray([3], 3) ..对吗?

最佳答案

当传递给函数时,数组会退化为指针,指针本质上不存储长度。第二个参数将存储数组中元素的数量,因此,它看起来像这样:

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));

关于c - 数组简介,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9771624/

相关文章:

c - 函数的隐式声明 ‘mygets’ [-Wimplicit-function-declaration] mygets(str1);

java - issuesMostOften(int[] a) - java

python - 使用相应的行对 Python 列进行排序

java - 如何在 Java 中将 CSV 文件数据存储到数组中?

c - 从 C 到 D 的数组指针

C:扫描数组时忽略一个值

c++ - 如何编写命令行 shell 来捕获 'UP' 键以获取历史输入?

javascript - jQuery:如何创建每个项目有两个值的数组

C dlsym undefined symbol

c - 苹果操作系统 X : How is the tcpcb struct of a TCP connection obtained by a kernel extension?