我试图在数组中找到最大数字.我创建了一个函数,我使用以下代码:
int maxValue( int myArray [], int size)
{
int i, maxValue;
maxValue=myArray[0];
//find the largest no
for (i=0;i)
{
if (myArray[i]>maxValue)
maxValue=myArray[i];
}
return maxValue;
}
Run Code Online (Sandbox Code Playgroud)
但是我在)令牌之前遇到语法错误.我做错了什么,我甚至做得对吗?任何帮助将不胜感激.
您必须将至少有一个成员的有效数组传递给此函数:
#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int
maxValue(int myArray[], size_t size) {
/* enforce the contract */
assert(myArray && size);
size_t i;
int maxValue = myArray[0];
for (i = 1; i < size; ++i) {
if ( myArray[i] > maxValue ) {
maxValue = myArray[i];
}
}
return maxValue;
}
int
main(void) {
int i;
int x[] = {1, 2, 3, 4, 5};
int *y = malloc(10 * sizeof(*y));
srand(time(NULL));
for (i = 0; i < 10; ++i) {
y[i] = rand();
}
printf("Max of x is %d\n", maxValue(x, sizeof(x)/sizeof(x[0])));
printf("Max of y is %d\n", maxValue(y, 10));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
根据定义,数组的大小不能为负数.C中数组大小的适当变量是size_t,使用它.
你的for循环可以从数组的第二个元素开始,因为你已经maxValue用第一个元素初始化了.
for循环有三个部分:
for (initializer; should-continue; next-step)
Run Code Online (Sandbox Code Playgroud)
for循环相当于:
initializer;
while (should-continue)
{
/* body of the for */
next-step;
}
Run Code Online (Sandbox Code Playgroud)
所以正确的代码是:
for (i = 0; i < size; ++i)
Run Code Online (Sandbox Code Playgroud)