首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数组简介

数组简介
EN

Stack Overflow用户
提问于 2012-03-19 14:06:02
回答 3查看 484关注 0票数 0

可能重复:

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

所以我刚开始处理数组,我需要创建3个函数来让我学习。

代码语言:javascript
复制
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) ..。是那么回事吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-03-19 14:08:32

for sumarray,im困惑,因为数组在一定长度内存储某些内容,为什么需要第二个参数n

您需要第二个参数来告诉您数组的长度。数组作为C中方法的参数时,它们的长度不会附加在它们上。因此,如果您有一个以数组作为参数的方法,它无法知道长度,除非您也将其传递给该方法。这就是n的作用。

,以及如何测试一个消耗数组的函数,我的想法就像sumarray([3], 3) ..是这样吗?

不是的。你可以说

代码语言:javascript
复制
int myArray[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

然后

代码语言:javascript
复制
int sum = sumarray(myArray, 10);

要解决所有这些问题,您需要循环(最好使用for循环,我相信您的讲师提供了如何遍历数组元素的示例)。除此之外,我不做你的家庭作业。问具体的、有针对性的问题,我很乐意考虑回答它们。

票数 2
EN

Stack Overflow用户

发布于 2012-03-19 14:11:17

当传递给函数时,数组会衰减为指针,指针本身不存储长度。第二个参数将存储数组中的元素数,因此,它将如下所示:

代码语言:javascript
复制
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));
票数 10
EN

Stack Overflow用户

发布于 2012-03-19 14:08:56

im很困惑,因为数组在一定长度内存储某些东西,为什么需要第二个参数n?

因为你不知道一定的长度。如果您不想在更改初始数组的长度时更改代码,则需要传递n,因为c语言通常不提供该信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9771624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档