C ++错误:无法将'学生'转换为'学生*'... - 函数中的struct数组

时间:2016-06-29 16:04:29

标签: c++ arrays function struct reference

当我运行下面的代码时,我发现它会产生一个我不确定如何解决的错误。有人可以帮帮我吗?

代码

#include <iostream>
#include <cstdlib>

using namespace std;

const int n=5;

struct students
{
    string firstname;
    float rate;
};

students A[n];
students B[n];

void writeStudents(students *TAB){
    for(int i=0; i<n; i++){
        cout << "First name: ";
        cin >> TAB[i].firstname;
        cout << "Rate: ";
        cin >> TAB[i].rate;
    }
}

void printStudents(students *TAB, int rows, float difference){
    float average=0;
    for(int i=0; i<n; i++){
        average = average + TAB[i].rate;
    }
    average = average/n;
    for(int i=n-rows; i<n; i++){
        if(TAB[i].rate > average+difference){
           cout << TAB[i].firstname << endl;
        }
    }
}

int main()
{
    writeStudents(A[n]);
    writeStudents(B[n]);
    printStudents(A[n], 2, 0.9);
    printStudents(B[n], 3, 1.2);
    return 0;
}

控制台日志

error: cannot convert 'students' to 'students*' for argument '1' to 'void writeStudents(students*)' (line 54)
error: cannot convert 'students' to 'students*' for argument '1' to 'void writeStudents(students*)' (line 55)
error: cannot convert 'students' to 'students*' for argument '1' to 'void printStudents(students*)' (line 56)
error: cannot convert 'students' to 'students*' for argument '1' to 'void printStudents(students*)' (line 57)

3 个答案:

答案 0 :(得分:3)

在表达式中使用时,A[n]表示“索引A处的数组n的元素”。这有两个原因:首先,您在数组中获得单个元素,并将其传递给期望该数组的函数。第二个问题是索引n超出范围。

在调用函数时使用普通AB,例如

writeStudents(A);

答案 1 :(得分:0)

这个怎么样(作为第一步)?:

writeStudents(A);
writeStudents(B);
printStudents(A, 2, 0.9);
printStudents(B, 3, 1.2);

答案 2 :(得分:0)

这是你的问题:

writeStudents(A[n]);
writeStudents(B[n]);
printStudents(A[n], 2, 0.9);
printStudents(B[n], 3, 1.2);

请改为尝试:

writeStudents(A);
writeStudents(B);
printStudents(A, 2, 0.9);
printStudents(B, 3, 1.2);