【发布时间】:2021-04-15 06:11:42
【问题描述】:
以下程序旨在检查给定元素是否在给定数组中、元素出现的数组索引以及元素出现的次数。但是,它没有给出正确的结果。我尝试将 seqsearch 函数中的 poscount 替换为 *poscount 并对此指针数据类型进行了进一步更改。然后代码运行良好。为什么会这样?
#include <iostream>
using namespace std;
const int SIZE = 100;
void seqsearch(int[], int, int, int[], short);
int main() {
int array[SIZE], indices[SIZE];
int num, value;
short count = 0;
cerr << " Give number of elements in array : ";
cin >> num;
cerr << " Key in the array elements ";
for(int i = 0; i < num; i++) cin >> array[i];
cout << endl;
cerr << " Give the value to be searched : " << endl;
cin >> value;
cout << endl;
seqsearch(array, num, value, indices, count); // void function
if(count >= 0) {
cout << value << " found in array " << count << " times"
<< " at index positions " << endl;
for(int i = 0; i < count; i++) cout << indices[i] << " ";
cout << endl;
} else
cout << value << " not found in array " << endl;
return 0;
}
void seqsearch(int arr[], int size, int elm, int pos[], short poscount) {
int i, item;
poscount = 0;
for(i = 0; i < size; i++) {
if(arr[i] == elm) {
pos[poscount] = i;
poscount = poscount + 1;
}
}
return;
}
【问题讨论】: