请知道,我对 C 和一般指针还是很陌生...这是一个类,所以我不要求显式代码,只是帮助理解 概念。
我正在尝试创建一个循环以将随机值分配给结构中的 int。当我为我的指针或数组的当前迭代赋值时出现问题。
struct student{
int id;
int score;
};
struct student* allocate(){
/*Allocate memory for ten students*/
int ROSTER_SIZE = 10;
struct student *roster = malloc(ROSTER_SIZE * sizeof(struct student));
/*return the pointer*/
return roster;
}
void generate(struct student* students){
/*Generate random ID and scores for ten students, ID being between 1 and 10, scores between 0 and 100*/
int i = 0;
for (i = 0; i < 10; ++i) {
students[i]->id = i + 1;
students[i]->score = rand()%101;
}
现在,根据我的理解,这很可能是不正确的,我应该能够使用 students[i]
为每次迭代赋值,但是 VS 2010 告诉我“表达式必须有一个指针类型。”不是已经是指针了吗?它作为指针传递给函数,对吧?
最佳答案
改变:
students[i]->id = i + 1;
students[i]->score = rand()%101;
到:
students[i].id = i + 1;
students[i].score = rand()%101;
原因:students
是指向struct student
数组的指针。 students[i]
是一个实际的struct student
。请注意,students[i]
实际上等同于 *(students + i)
。
关于c - C 中的指针和循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12942369/