Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers and loops in C

Tags:

c

loops

pointers

Please know that I'm still very new to C and pointers in general... This is for a class so I'm not asking for explicit code, only help understanding the concepts.

I'm trying to create a loop to assign random values to an int within a struct. The problem occurs when I'm assigning values to the current iteration of my pointer or array.

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;
}

Now, from my understanding, which is most likely incorrect, I should be able to use students[i] to assign values to each iteration, but VS 2010 tells me "the expression must have a pointer type." Isn't it already a pointer? It's passed into the function as a pointer, right?

like image 895
idigyourpast Avatar asked Oct 17 '12 20:10

idigyourpast


2 Answers

Change:

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

to:

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

Reason: students is a pointer to an array of struct student. students[i] is an an actual struct student. Note that students[i] is actually equivalent to *(students + i).

like image 61
Paul R Avatar answered Sep 29 '22 20:09

Paul R


students is a pointer, but when you index it then you are refering to an actual instance of the structure, so hence you'll need to use . instead of -> to access a field in that structure

like image 42
hexist Avatar answered Sep 29 '22 22:09

hexist