<< Chapter < Page Chapter >> Page >

In the example above we are filling the structure variable tempStudent with values. At the end of the function, the value of tempStudent is returned as the return value of the function. The code to input 100 students can now be modified to use this function:

Student students[100];int i; for (i=0; i<100; i++) { students[i]= inputStudent(); }

The arrow operator

In order to dereference a pointer we would normally use the dereferencing operator (*) and if we our pointer was to a structure, we could subsequently use the dot '.' operator to refer to a member of the structure. Suppose we have declared a pointer which could be used to point to a structure of type employee as follows.

Student stuVariable; Student *stuPtr;stuPtr =&stuVariable;

To refer to the student identification we could say:

(*stuPtr).studentID

Note that the brackets are necessary because the dereference operator has lower precedence than the dot operator. This form of syntax is a little cumbersome, so another operator is provided to us as a convenient shorthand:

stuPtr->studentID

This method of accessing the number member through a pointer is completely equivalent to the previous form. The '->' operator is called the indirect member selection operator or just the arrow operator and it is almost always used in preference to the previous form.

Passing structures by reference

Passing structures to a function using pass-by-value can be simple and successful for simple structures so long as we do not wish to do so repeatedly. But when structures can contain a large amount of data (therefore occupying a large chunk of memory) then creating a new copy to pass to a function can create a burden on the memory of the computer. If we were going to do this repeatedly (say several thousand times within the running of a computer) then there would also be a cost in time to copy the structure for each function call.

In the example at the beginning of this section we created and filled a structure variable called tempStudent. When the function ended it returned the value of tempStudent. The same inefficiency exists with the return value from the function, where the Student structure must be copied to a local variable at the function call.

Whether such inefficiencies are of any significance or not depends on the circumstances and on the size of the structure. Each Student structure probably occupies about 50 bytes, so this is a reasonably significant amount of memory to be copying each time the output function is called or each time the input function returns, especially if this is happening frequently.

A better solution would be to pass the Student structure by reference, which means we will pass a pointer to the structure.

We can now revise the input function by passing an Student structure by reference using a pointer. Because the function is no longer returning an Student structure, we can also enhance the function to return a Boolean status indicating whether an Student structure was successfully read or not. We can enhance our function to do some better error checking. Below is the revised version.

bool inputStudent(Student *stuPtr) {printf("Enter Student identification: "); if (scanf("%s",&stuPtr->studentID) != 1) return false; printf("Enter Student name: ");fflush(stdin);gets(stuPtr->name); printf("Enter mark: ");if (scanf("%f",&stuPtr->markCS) != 1) return false; printf("Enter birth date: ");if (scanf("%i/%i/%i",&stuPtr->dateOfBirth.day,&stuPtr->dateOfBirth.month,&stuPtr->dateOfBirth.year) != 3) return false;return true; }

The code to input 100 students can now be revised as follows.

Student students[100];int i; for (i=0; i<100; i++) {while (!inputStudent(&students[i])){ printf("Invalid student details - try again!\n");fflush(stdin); }}

As a final example, consider a function to give s student a mark rise. The function takes two parameters. The first is an Student structure passed by reference, (a pointer to an Student structure) and the second is the increase of mark.

void markRise(Student *stuPtr, float increase) {stuPtr->markCS += increase; }

What use is such a function? Having input many students into an array, we might then wish to give certain students a mark rise. For each student we can easily call this function, passing a pointer to the appropriate Student structure.

Enumerated types

Another way of creating a new type is by creating an enumerated type. With an enumerated type we build a new type from scratch by stating which values are in the type. The syntax for an enumerated type is as follows.

enum TypeIdentifier { list... };

Here is an example of a definition of an enumerated type that can be used to refer to the days of the week.

enum DayOfWeek {sun, mon, tue, wed, thu, fri, sat};

Just like when we define a structure type, defining an enumerated type does not give us any space to store information. We use the type like a template to create variables of that type.

For instance we can create a variable of type DayOfWeek as follows.

DayOfWeek nameOfDay;

With variables of enumerated types we can do almost anything we could do with a variable of a basic data type. For instance we can assign a value as follows.

nameOfDay = tue;

Note that tue is a literal value of type DayOfWeek and we do not need to place quotes around it.

The values in DayOfWeek are ordered and each has an equivalent int value; sun==0, mon==1, and so on. The value of sun is less than the value of wed because of the order they were presented in the list of values when defining the type. We can compare two values of enumerated types as follows:

DayOfWeek day1, day2; // Get day values... if(day1<day2) { ...}

Here is another example that uses enumerated types.

#include<stdio.h>#include<conio.h>enum TrafficLight {red, orange, green}; int main(){ TrafficLight light;printf("Please enter a Light Value: (0)Red (1)Orange (2)Green:\n"); scanf("%i",&light); switch(light){ case red:printf("Stop!\n"); break;case orange: printf("Slow Down\n");break; case green:printf("Go\n"); }getch(); }

Questions & Answers

A golfer on a fairway is 70 m away from the green, which sits below the level of the fairway by 20 m. If the golfer hits the ball at an angle of 40° with an initial speed of 20 m/s, how close to the green does she come?
Aislinn Reply
cm
tijani
what is titration
John Reply
what is physics
Siyaka Reply
A mouse of mass 200 g falls 100 m down a vertical mine shaft and lands at the bottom with a speed of 8.0 m/s. During its fall, how much work is done on the mouse by air resistance
Jude Reply
Can you compute that for me. Ty
Jude
what is the dimension formula of energy?
David Reply
what is viscosity?
David
what is inorganic
emma Reply
what is chemistry
Youesf Reply
what is inorganic
emma
Chemistry is a branch of science that deals with the study of matter,it composition,it structure and the changes it undergoes
Adjei
please, I'm a physics student and I need help in physics
Adjanou
chemistry could also be understood like the sexual attraction/repulsion of the male and female elements. the reaction varies depending on the energy differences of each given gender. + masculine -female.
Pedro
A ball is thrown straight up.it passes a 2.0m high window 7.50 m off the ground on it path up and takes 1.30 s to go past the window.what was the ball initial velocity
Krampah Reply
2. A sled plus passenger with total mass 50 kg is pulled 20 m across the snow (0.20) at constant velocity by a force directed 25° above the horizontal. Calculate (a) the work of the applied force, (b) the work of friction, and (c) the total work.
Sahid Reply
you have been hired as an espert witness in a court case involving an automobile accident. the accident involved car A of mass 1500kg which crashed into stationary car B of mass 1100kg. the driver of car A applied his brakes 15 m before he skidded and crashed into car B. after the collision, car A s
Samuel Reply
can someone explain to me, an ignorant high school student, why the trend of the graph doesn't follow the fact that the higher frequency a sound wave is, the more power it is, hence, making me think the phons output would follow this general trend?
Joseph Reply
Nevermind i just realied that the graph is the phons output for a person with normal hearing and not just the phons output of the sound waves power, I should read the entire thing next time
Joseph
Follow up question, does anyone know where I can find a graph that accuretly depicts the actual relative "power" output of sound over its frequency instead of just humans hearing
Joseph
"Generation of electrical energy from sound energy | IEEE Conference Publication | IEEE Xplore" ***ieeexplore.ieee.org/document/7150687?reload=true
Ryan
what's motion
Maurice Reply
what are the types of wave
Maurice
answer
Magreth
progressive wave
Magreth
hello friend how are you
Muhammad Reply
fine, how about you?
Mohammed
hi
Mujahid
A string is 3.00 m long with a mass of 5.00 g. The string is held taut with a tension of 500.00 N applied to the string. A pulse is sent down the string. How long does it take the pulse to travel the 3.00 m of the string?
yasuo Reply
Who can show me the full solution in this problem?
Reofrir Reply
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Introduction to computer science. OpenStax CNX. Jul 29, 2009 Download for free at http://cnx.org/content/col10776/1.1
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Introduction to computer science' conversation and receive update notifications?

Ask