我的教授要求我创建函数并使用指向为每个函数传递一个整数数组作为参数,但是当我插入他创建的测试代码时,我得到了“ 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 *numArr[]
void Homework::print_array(int numArr[], int size) //remove the extra * on front
{
// 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;
}
好,如果您必须使用int *numArr[]
,然后保留原始print_array函数,但是如果尝试打印它,请使用h.print_array(&a, 10);
。
如果您的教授想显示指针,您可以这样做:
void Homework::print_array(int *numArr, int size)//exact same as int numArr[] as it decays to a pointer
{
for (int count = 0; count < size; count++) {
if (count == 0) {
cout << numArr[count];
}
else {
cout << ", " << numArr[count];
}
}
cout << endl;
}
int main()
{
int a[10] = { 3, 5, 6, 8, 12, 13, 16, 17, 18, 20 };
Homework h;
h.print_array(a, 10);
return 0;
}
编辑:认为您的教授可能希望您演示这样的指针数组:
void Homework::print_array(int *numArr[], int size)
{
for (int count = 0; count < size; count++) {
if (count == 0) {
cout << *numArr[count];
}
else {
cout << ", " << *numArr[count];
}
}
cout << endl;
}
int main()
{
int a[10] = { 3, 5, 6, 8, 12, 13, 16, 17, 18, 20 };
int* arrayPtr[10];
for(int i=0; i<10; i++){
arrayPtr[i] = &a[i];
}
Homework h;
h.print_array(arrayPtr, 10);
return 0;
}