This is a code I wrote today. The problem is as follows: The school is doing the project. Each teacher leads 5 students, a total of 3 teachers. The demand is as follows. Design the structure of students and teachers. In the structure of teachers, there are teachers' names and an array of 5 students as members Students' members have names and test scores. Create an array to store 3 teachers, and assign values to each teacher and students through functions Finally, print out the teacher data and the student data brought by the teacher., When I replace value delivery with address delivery, the error code is as follows:
#include<iostream>;
using namespace std;
#include<string>;
#include<ctime>;
struct Student {
string name;
int score;
};
struct Teacher {
string name;
struct Student sArray[5];
};
void printTeacher(struct Teacher tArray[], int len) {
for (int i = 0; i < len; i ) {
cout << "老师的姓名为" << tArray[i].name << endl;
for (int j = 0; j < 5; j ) {
cout << "\t学生的姓名为:" << tArray[i].sArray[j].name << " 学生的成绩为:" << tArray[i].sArray[j].score << endl;
}
}
}
void allocateSpace(struct Teacher * tArray[], int * len) {
string nameseed = "ABCDE";
string tname = "教师";
string sname = "教师";
for (int i = 0; i < * len; i ) {
tArray[i] -> name = tname nameseed[i];
for (int j = 0; j < 5; j ) {
tArray[i] -> sArray[j].name = sname nameseed[j];
tArray[i] -> sArray[j].score = rand() % 61 40;
}
}
}
int main() {
srand((unsigned int) time(NULL)); //随机数种子 头文件 #include <ctime>
struct Teacher tArray[3];
int len = sizeof(tArray) / sizeof(tArray[0]);
cout << tArray << endl;
allocateSpace(tArray, & len);
printTeacher(tArray, len);
system("pause");
return 0;
}
allocateSpace(tArray, &len);
Here I am prompted that arguments and formal parameters are incompatible.
Why and how?
CodePudding user response:
The problem is that &tArray
is a pointer to an array of 3 Teacher
elements,
i.e. a Teacher (*)[3]
while your parameter is of type Teacher**
. You may
try this:
void allocateSpace(struct Teacher* tArray, int len) {
// ^ no need for len to be a pointer
string nameseed = "ABCDE";
string tname = "??";
string sname = "??";
for (int i = 0; i < len; i ) {
tArray[i]. name = tname nameseed[i];
for (int j = 0; j < 5; j ) {
tArray[i]. sArray[j].name = sname nameseed[j];
tArray[i]. sArray[j].score = rand() % 61 40;
}
}
}
// ...
// Here, tArray automatically decays to a pointer to its first
// element, i.e. to &tArray[0]:
allocateSpace(tArray, len);
CodePudding user response:
You take the array by pointer, same as the length parameter so you have to also pass it the same way.
allocateSpace(&tArray, &len);
^pointer to array