#include <iostream>
#include <string>
using namespace std;
// Declaration of the function indexvalue()
int *maxArr(int [], const int);
// Another function used to print out an error message
void
problem(string str) {
cout << str << endl;
exit(1);
}
const int Size = 10;
int main()
{
int a[Size] = {23, 45, 12, 76, 9, 131, 10, 8, 23, 4};
int *b, i;
string error1("Problem with maxArr(), wrong subscript");
string error2("Problem with maxArr(), output should be NULL");
// Call the function multiple times with different input
// Note the use of pointer arithmetic
if (maxArr(a,Size)!= a+5) problem(error1);
if (maxArr(a,Size-5)!= a+3) problem(error1);
if (maxArr(a+6,4)!= a+8) problem(error1);
if (maxArr(a,0)!= NULL) problem(error2);
// The function passed all the tests
cout << "The function passed all the tests in this program\n" << endl;
exit(0);
}
int *maxArr(int arr[], int size){
int max = 0;
int index = 0;
if ( size < 0)
return NULL;
for (int i = 0; i < size; i++) {
if (arr[i] > max )
{
max = arr[i];
index = i;
}
return arr + i;
}
}maxArr()的规范
该函数接受整数数组和元素数量作为参数。此函数返回int的地址,该地址指向数组的最大值。
我试图找出maxArr()函数的错误所在,到目前为止,我唯一更正的是将if ( <= < 0)更改为if(size <= 0)为了处理null的情况,我不知道如何更正该函数以解决error1消息。任何帮助都将不胜感激。
发布于 2013-10-27 06:39:10
您将从函数maxArr中的for循环内部返回。它总是会在第一次迭代中返回。另外,您应该返回arr+index而不是arr+i。
for (int i = 0; i < size; i++)
{
if (arr[i] > max )
{
max = arr[i];
index = i;
}
//return arr + i;
// ^^^^ Wrong
}
return arr+index; //return from here检查返回NULL的操作将会失败,这是您当前的情况。您应该像这样检查:
if ( size <= 0)
return NULL;发布于 2013-10-27 06:43:43
这里有一个括号问题:
for (int i = 0; i < size; i++) {
if (arr[i] > max )
{
max = arr[i];
index = i;
}
return arr + i;
}您的返回位于for循环中,因此您将在循环的第一次迭代中返回。
如果不使用索引,您可能希望将return语句移出主循环并返回arr + index;
https://stackoverflow.com/questions/19612613
复制相似问题