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

how does Neisseria cause meningitis
Nyibol Reply
what is microbiologist
Muhammad Reply
what is errata
Muhammad
is the branch of biology that deals with the study of microorganisms.
Ntefuni Reply
What is microbiology
Mercy Reply
studies of microbes
Louisiaste
when we takee the specimen which lumbar,spin,
Ziyad Reply
How bacteria create energy to survive?
Muhamad Reply
Bacteria doesn't produce energy they are dependent upon their substrate in case of lack of nutrients they are able to make spores which helps them to sustain in harsh environments
_Adnan
But not all bacteria make spores, l mean Eukaryotic cells have Mitochondria which acts as powerhouse for them, since bacteria don't have it, what is the substitution for it?
Muhamad
they make spores
Louisiaste
what is sporadic nd endemic, epidemic
Aminu Reply
the significance of food webs for disease transmission
Abreham
food webs brings about an infection as an individual depends on number of diseased foods or carriers dully.
Mark
explain assimilatory nitrate reduction
Esinniobiwa Reply
Assimilatory nitrate reduction is a process that occurs in some microorganisms, such as bacteria and archaea, in which nitrate (NO3-) is reduced to nitrite (NO2-), and then further reduced to ammonia (NH3).
Elkana
This process is called assimilatory nitrate reduction because the nitrogen that is produced is incorporated in the cells of microorganisms where it can be used in the synthesis of amino acids and other nitrogen products
Elkana
Examples of thermophilic organisms
Shu Reply
Give Examples of thermophilic organisms
Shu
advantages of normal Flora to the host
Micheal Reply
Prevent foreign microbes to the host
Abubakar
they provide healthier benefits to their hosts
ayesha
They are friends to host only when Host immune system is strong and become enemies when the host immune system is weakened . very bad relationship!
Mark
what is cell
faisal Reply
cell is the smallest unit of life
Fauziya
cell is the smallest unit of life
Akanni
ok
Innocent
cell is the structural and functional unit of life
Hasan
is the fundamental units of Life
Musa
what are emergency diseases
Micheal Reply
There are nothing like emergency disease but there are some common medical emergency which can occur simultaneously like Bleeding,heart attack,Breathing difficulties,severe pain heart stock.Hope you will get my point .Have a nice day ❣️
_Adnan
define infection ,prevention and control
Innocent
I think infection prevention and control is the avoidance of all things we do that gives out break of infections and promotion of health practices that promote life
Lubega
Heyy Lubega hussein where are u from?
_Adnan
en français
Adama
which site have a normal flora
ESTHER Reply
Many sites of the body have it Skin Nasal cavity Oral cavity Gastro intestinal tract
Safaa
skin
Asiina
skin,Oral,Nasal,GIt
Sadik
How can Commensal can Bacteria change into pathogen?
Sadik
How can Commensal Bacteria change into pathogen?
Sadik
all
Tesfaye
by fussion
Asiina
what are the advantages of normal Flora to the host
Micheal
what are the ways of control and prevention of nosocomial infection in the hospital
Micheal
what is inflammation
Shelly Reply
part of a tissue or an organ being wounded or bruised.
Wilfred
what term is used to name and classify microorganisms?
Micheal Reply
Binomial nomenclature
adeolu
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