Need some clarity on structures

Really noob question, but I'm having trouble understanding structures.

I defined the struct in the header as a global variable:

1
2
3
4
5
6
7
8
struct studentInfo
    {
        int highestGrade;
        int highestGradeLocation;
        int lowestGrade;
        int lowestGradeLocation;
        int averageScore;
    };


What is the proper syntax to give the different variables a value within a function?

From what I've seen I thought it'd be like:

 
studentInfo.highestGrade = 99;


But I'm obviously getting it wrong. Perhaps it's not as straightforward as I thought.

I may be passing it wrong too.

From what I gather the syntax for it would be similar to:

1
2
3
4
5
//Defining prototype
void Grades(struct studentInfo)

//Calling
Grades(studentInfo)


Where I'm trying to pass the entire structure.
Last edited on
I defined the struct in the header as a global variable:

No, that syntax defines a new type, called "studentInfo", and no variables of that type.

From what I've seen I thought it'd be like:
studentInfo.highestGrade = 99;

First create a variable, then you can access its members:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct studentInfo
    {
        int highestGrade;
        int highestGradeLocation;
        int lowestGrade;
        int lowestGradeLocation;
        int averageScore;
    };
void Grades(studentInfo) {}
int main()
{
    // first create a variable
    studentInfo v1;
    // then access its members
    v1.highestGrade = 99;

    // or you can set every member right away
    studentInfo v2 = {99, 10, 10, 4, 12};

    Grades(v2); // calling a function
}

demo: http://ideone.com/b6opfC
@hanipman,

Structs, when passed to functions, should be passed by reference. To see why, run this code demo. You will notice that the struct (if not passed by reference) will not be properly modified by the function calling to use it.
When you run this code you will notice that only two of the variables are changed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>

typedef struct studentInfo
    {
        int highestGrade;
        int highestGradeLocation;
        int lowestGrade;
        int lowestGradeLocation;
        int averageScore;
    } studentInfo;
	
void incorrectGradesFunction( studentInfo  s ){
	s.highestGrade = 99;
}

void correctGradesFunction( studentInfo* s ){
	s->averageScore = 55;
	(*s).lowestGrade = 0;
}


int main( void ){
	studentInfo sStruct;
	incorrectGradesFunction(sStruct);
	correctGradesFunction(&sStruct);
	
	printf("Output Not Modified: %d\n", sStruct.highestGrade);
	printf("Average: %d\n",sStruct.averageScore);
	printf("Lowest: %d\n", sStruct.lowestGrade);
	
	return 0;
}
Last edited on
Topic archived. No new replies allowed.