指针和循环在C

前端之家收集整理的这篇文章主要介绍了指针和循环在C前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请注意,我还是很新的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;
}

现在,根据我的理解,最有可能是错误的,我应该能够使用学生[i]为每个迭代分配值,但VS 2010告诉我“表达式必须有一个指针类型”.它不是一个指针吗?它作为一个指针传递给函数,对吗?

解决方法

更改:
students[i]->id = i + 1;
students[i]->score = rand()%101;

至:

students[i].id = i + 1;
students[i].score = rand()%101;

原因:学生是一个指向一系列结构学生的指针.学生[i]是一名实际的结构学生.请注意,学生[i]其实相当于*(学生我).

原文链接:https://www.f2er.com/c/112340.html

猜你在找的C&C++相关文章