【发布时间】:2023-03-03 05:02:23
【问题描述】:
我试图在以下代码中尽可能使用指针,但很难弄清楚如何准确地建立指针以及如何在我的第一个函数结束时返回指针值。我已经对此主题进行了一些研究,但到目前为止我发现的方法都没有帮助,所以我希望你能有一些专门的提示。
注意:我是初学者。
#include <iostream>
using namespace std;
int mode(int *pies[], int size) {
int count = 1;
int max = 0;
int *mode=pies[0];
for (int i=0; i<size-1; i++)
{
if (pies[i] == pies[i+1])
{
count++;
if (count>max)
{
max = count;
mode = pies[i];
}
}
else
count = 1;
}
return *mode;
}
int main() {
int n;
cout<<"Input the number of people: "<<endl;
cin>>n;
int survey[n];
cout << "Enter the amount of pie eaten by each person:" << endl;
for(int i = 0; i < n; i++) {
cout <<"Person "<<(i + 1)<< ": "<<endl;
cin>>survey[i];
}
cout<<"Mode: "<<mode(survey, n)<< endl;
return 0;
}
【问题讨论】:
-
尽可能使用指针 为什么? :/ 无论如何,如果你想返回一个指针,那么就以你返回任何其他数据类型的方式返回一个指针。当然,您还必须将函数的返回类型更改为指针。
-
mode接受int**参数,您传递的是int*。 -
只要使用--int模式(int* pies, int size)
-
使用
std::vector<int>。它是 C++,而不是 C。 -
方便阅读:What is array to pointer decay? TL;DR 版本:数组不是指针,而是根据需要隐式转换为指针。结果,您几乎从不传递数组,因为您悄悄地传递了指向数组的指针。这种行为可能很烦人,但在过去没有资源按值传递数组时,这种行为非常有意义。