【发布时间】:2020-06-09 01:15:28
【问题描述】:
我的教授要求我创建函数并使用指针 为每个函数传递一个整数数组作为参数,但是当我插入他创建的测试代码时,我得到了“int*”类型的参数与“int**”类型的参数不兼容的错误。
#include <iostream>
#include "homework.h"
using namespace std;
int main() {
int a[10] = { 3, 5, 6, 8, 12, 13, 16, 17, 18, 20 };
int b[6] = { 18, 16, 19, 3 ,14, 6 };
int c[5] = { 5, 2, 4, 3, 1 };
Homework h;
// testing initialize_array
h.print_array(a, 10); // ERROR
h.initialize_array(a, 10); // ERROR
h.print_array(a, 10); // ERROR
h.print_array(b, 6); // ERROR
h.selection_sort(b, 6); // ERROR
h.print_array(b, 6); // ERROR
cout << "Factorial of 5 = " << h.factorial (5) <<endl; //print: 120
c[0] = h.factorial(c[0]);
c[1] = h.factorial(c[2]);
h.print_array(c, 5); // ERROR
return 0;
})
这是作业的源文件:
#include <iostream>
#include "homework.h"
using namespace std;
void Homework::initialize_array(int *numArr[], int size)
{
for (int count = 0; count < size; count++) {
// if divisible by 2, replace the value to 0.
if (count % 2 == 0) {
*numArr[count] = 0;
}
else {
*numArr[count] = 1;
}
}
}
void Homework::print_array(int *numArr[], int size)
{
// prints each values in the array.
for (int count = 0; count < size; count++) {
if (count == 0) {
cout << *numArr[count];
}
else {
cout << ", " << *numArr[count];
}
}
cout << endl;
}
void Homework::selection_sort(int *numArr[], int size)
{
int i, j, minIndex;
// determine the minimum value.
for (i = size - 1; i > 0; i--) {
minIndex = 0;
for (j=1; j<=i; j++) {
if (*numArr[j] < *numArr[minIndex])
minIndex = j;
}
// swap values.
int temp = *numArr[minIndex];
*numArr[minIndex] = *numArr[i];
*numArr[i] = temp;
}
}
int Homework::factorial(int num)
{
if (num == 0 || num == 1)
return 1;
else
// if not 0 or 1, recall the function.
return(num * factorial(num - 1));
}
【问题讨论】:
-
你正在处理一个 int 数组,它正在寻找一个指向 int 数组的指针
-
在函数参数中,
int*[]只是int**的语法糖。这在需要更改调用者指向数组的指针的函数中使用是有意义的,但这对于本作业中的任何函数都没有意义。显示的所有Homework方法都应该使用int[]参数,这是int*的语法糖。int[]数组衰减为指向其第一个元素的int*指针,这是所有这些方法所需要的。如果您完全按照教授给您的方式使用Homework课程,那么他给您的代码很糟糕(嗯,误导) -
我的教授提供了主课,但我上次按照 Remy 说的做,因为没有使用指针将数组作为参数传递而丢分。