在数组C编程中查找最大数量

Zac*_*ith -1 c

我试图在数组中找到最大数字.我创建了一个函数,我使用以下代码:

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)

但是我在)令牌之前遇到语法错误.我做错了什么,我甚至做得对吗?任何帮助将不胜感激.

Sin*_*nür 7

您必须将至少有一个成员的有效数组传递给此函数:

#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用第一个元素初始化了.

  • 请注意,这假设您的数组至少包含一个元素:http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Zero-Length.html (2认同)
  • 为什么不用i ++或++ i而不是i + = 1? (2认同)

R S*_*hko 5

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)