使用指针调用函数时出现错误
问题描述:
所以即时通讯对C++来说仍然很新颖,并且现在已经在执行一段程序。我认为我正在慢慢获得它,但不断收到错误“智能感知:'*'的操作数必须是指针。”在第36行第10列。我需要做些什么来解决这个错误?我就要去其他的功能,因为我完成了额外的函数声明每一个难过使用指针调用函数时出现错误
// This program will take input from the user and calculate the
// average, median, and mode of the number of movies students see in a month.
#include <iostream>
using namespace std;
// Function prototypes
double median(int *, int);
int mode(int *, int);
int *makeArray(int);
void getMovieData(int *, int);
void selectionSort(int[], int);
double average(int *, int);
// variables
int surveyed;
int main()
{
cout << "This program will give the average, median, and mode of the number of movies students see in a month" << endl;
cout << "How many students were surveyed?" << endl;
cin >> surveyed;
int *array = new int[surveyed];
for (int i = 0; i < surveyed; ++i)
{
cout << "How many movies did student " << i + 1 << " see?" << endl;
cin >> array[i];
}
median(*array[surveyed], surveyed);
}
double median(int *array[], int num)
{
if (num % 2 != 0)
{
int temp = ((num + 1)/2) - 1;
cout << "The median of the number of movies seen by the students is " << array[temp] << endl;
}
else
{
cout << "The median of the number of movies seen by the students is " << array[(num/2) - 1] << " and " << array[num/2] << endl;
}
}
答
问题:
-
在下面的行中使用的表达
*array[surveyed]
:median(*array[surveyed], surveyed);
是不正确的。
array[surveyed]
是数组中的surveyed
个元素。它不是一个指针。解引用它是没有意义的。 -
声明中使用的第一个参数
median
的类型与定义中使用的类型不同。该声明似乎是正确的。实施更改为:double median(int *array, int num)
-
解决您拨打
median
的方式。取而代之的median(*array[surveyed], surveyed);
使用
median(array, surveyed);
+0
非常感谢你。也意识到我已经忘记了在函数结束时返回,所以添加好ol后返回0;我能够让它运行。有时间转到下一个功能。 =) – exo316 2015-02-11 19:45:02
所以'array'是int'的'数组。在第36行中,你可以执行'* array [surveyed]'。这在调查的索引处访问阵列数组(在这里是错误的命名)。这给出了一个int,然后*尝试去引用。 int是一个原始类型,它不是一个指针,所以不能被去引用。 – 2015-02-11 19:34:55
喵,将'array [surveyed]'改为'array'。 – WhozCraig 2015-02-11 19:37:35
'所以即时通讯对C++来说还是个新鲜事物,并且已经做了一段时间的程序了'所以你说你找不到几十万个例子中的一个例子,向你展示传递一个数组的正确方法,如何正确声明功能? – PaulMcKenzie 2015-02-11 19:37:39