【发布时间】:2022-01-18 06:30:59
【问题描述】:
该函数应该接受一个数组并返回其中的最大值。
int findMaxValue(int listName[], int listSize){
int largestVal = listName[0];
for (int index = 0; index < listSize; ++index){
if(listName[index] > largestVal){
largestVal = listName[index];
//printf ("%d\n", largestVal);
}
}
//printf ("%d\n", largestVal); it wouldn't even give any output
return largestVal;
}
int main{
int theArray = {3, 6, 7, 8, 7, 9, 3, 4, 8};
int sizeArr = (sizeof(theArray) / sizeof(int));
findMaxValue(theArray, sizeArr);
}
我看到数组在传递时会变成一个指针,但是编译器想要什么?我遇到了错误:
prog4TSR.c:75:42: note: (near initialization for 'theArray')
prog4TSR.c:75:45: warning: excess elements in scalar initializer
int theArray = {3, 6, 7, 8, 7, 9, 3, 4, 8};
^
prog4TSR.c:75:45: note: (near initialization for 'theArray')
prog4TSR.c:78:18: warning: passing argument 1 of 'findMaxValue' makes pointer from integer without a cast [-Wint-conversion]
findMaxValue(theArray, sizeArr);
^~~~~~~~
prog4TSR.c:6:5: note: expected 'int *' but argument is of type 'int'
int findMaxValue(int listName[], int listSize){
【问题讨论】:
-
int theArray[] = {3, 6, 7, 8, 7, 9, 3, 4, 8}; -
int theArray不是数组,它是单个 int。int theArray[] = { ... };是一个数组。一旦你解决了其他问题应该消失。 -
小问题。在访问
findMaxValue中的数组之前检查大小,以防万一它为空,并且由于您正在获取第一个值,因此您可以在索引 1 而不是 0 处开始循环。