structures and enumerations introduction structure definitions nested structure referring and...

25
Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function Using typedef Example using structure Enumeration constants

Upload: kerry-curtis

Post on 18-Jan-2016

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Structures and Enumerations

Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function Using typedef Example using structure Enumeration constants

Page 2: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Introduction So far we have only used data types which have

been defined by C such as int, double, char and etc. It is also possible to create our own data types - user

defined data type. We must declare data types as structures or is called

a structure. A structure can contain both built-in data types and

another structure. The concept of structure is pretty much the same as

arrays except that in an array, all the data is of the same types but in a structure, the data can be of different types.

Page 3: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Structure Definition

General syntax:struct structure_name {

data_type element1;

data_type element2;

. . .

};

Example:Structure definition:

struct student {

char name[20];

int studentID;

char major[50];

};

Structure variable declarartion:

struct student my_student;

Page 4: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Structure Definition

Example:

struct student {

char name[20];

int studentID;

char major[50];

} my_student;

Page 5: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Nested Structurestruct address {

char address1[50];

char address2[50];

int postcode;

char town[50];

char state[50];

};

struct student {

char name[20];

int studentID;

char major[50];

struct address addr;

} my_student;

Page 6: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

struct student {

char name[20];

int studentid;

char major[50];

struct address {

char address1[50], address2[50], town[50], state[50];

int postcode;

} addr;

};

struct student my_student;

Page 7: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Referring and Initializing Structure Elements

A structure contains many elements. Each elements of a structure can be referred to by using the operator “.”

Let us use the structure student which we have seen before as an example:

struct student my_student;

my_student.name;

my_student.studentID;

Page 8: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Therefore, we can initialize each elements of a structure individually such as:

struct address my_addr={“xxxx”,”yyy”,123,”Bangi”,”selangor”};

struct student my_student;my_student.studentID = 10179;my_student.addr = my_addr;

Or we can initialize the structure while we are creating an instance of the structure:

struct address my_addr ={“xxxx”,”yyy”,123,”Bangi”,”selangor”};;

struct student my_student = {“Salman”, 10179, “IT”, my_addr}

Notice that it is possible to use the ‘=’ operator on a struct variable. When the ‘=’ sign is used, each elements of the structure at the right hand side is copied into the structure at the left hand side.

Page 9: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Passing Structures to a Function We can pass the student structure that we have

created before to a function called Read() as follows:

void Read(struct student s1);

In the function above, a copy of the student structure will be created locally for the use of the function. But any changes to the structure inside the function will not affect the actual structure.

It is also possible to use pointers and pass the reference of the structure to the function. This way, any changes inside the function will change the actual structure as well.

Page 10: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

To pass a reference, the Read() function can be written this way:

void Read(struct student *s1);

Take note that when a structure is declared as a pointer, the elements in the structure cannot be referred to using the ‘.’ operator anymore. Instead, they need to be accessed using the ‘->’ operator.

For example:void Read(struct student *s1) {

s1->studentID = 10179;

scanf(“%s”, s1->name);

scanf(“%s”, s1->major);

}

Page 11: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Passing Structures to a Function#include<stdio.h>typedef struct student{

int studentid;char name[20];int score;char grade;

} StudentData;void DecideGrade(StudentData *);

void main(){StudentData x;scanf(“%d%s%d”, &x.studentid, x.name, &x.score);DecideGrade(&x);printf(“The grade is %c\n”, x.grade);

}void DecideGrade(StudentData *p) {

if(p->score>90) p->grade=‘A’;else if(p->score>80) p->grade=‘B’;else if(p->score>70) p->grade=‘C’;else if(p->score>60) p->grade=‘D’;else p-<grade=‘F’;

}

Page 12: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Using typedef in Structure Declarations The keyword typedef provides a mechanism

for creating synonyms (aliases) for previously defined data types.

Here is an example on how to use typedef when declaring a structure:

typedef struct student {

char name[20];

int studentID;

char major[50];

struct address addr;

} StudentData;

Page 13: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

By using typedef, we now do not have to write the word “struct” before declaring a struct variable. Instead of writing:

struct student my_student;

we can now write:

StudentData my_student;

Same thing with passing the structure to a function:

void Read(StudentData *s1);

Page 14: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Example Using Structure#include <stdio.h>#define NUM_STUDENTS 20

typedef struct student {int studentID;char name[30];int score;char grade;

} StudentData;

void main(void) {StudentData students[NUM_STUDENTS];int i;

Read(students);DecideGrade(students);

}

Page 15: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

void Read(StudentData students[]) {int i;for (i = 0; i < NUM_STUDENTS; i++) {

printf(“Enter the studentID: “);scanf(“%d”, &students[i].studentID);printf(“Enter the name: “);scanf(“%s”, students[i].name);printf(“Enter the score: “);scanf(“%d”, &students[i].score);

}}

void DecideGrade(StudentData students[]) {int i;for (i = 0; i < NUM_STUDENTS; i++) {

if (students[i].score > 90) students[i].grade = ‘A’;else if (students[i].score > 80) students[i].grade = ‘B’;else if (students[i].score > 65) students[i].grade = ‘C’;else if (students[i].score > 50) students[i].grade = ‘D’;else students[i].grade = ‘F’;

}}

Page 16: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Enumerations An enumeration, introduced by the keyword

enum, is a set of integer constants represented by identifiers.

Example:typedef enum islamic_months {

muharam, safar, rabiulawal, rabiulakhir,

jamadilawal, jamadilakhir, rejab, syaaban,

ramadhan, syawal, zulkaedah, zulhijjah

} ISLAMIC_CAL;

Each of the identifiers actually has a value, starting with 0 (unless specified otherwise). Therefore, we can treat them as integers.

Page 17: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

If we want the enumeration to start with a value other than 0, we can assign the value to the first identifier:enum islamic_months {

muharam = 1, safar, rabiulawal, rabiulakhir,

jamadilawal, jamadilakhir, rejab, syaaban,

ramadhan, syawal, zulkaedah, zulhijjah

};

Same as with the other data types, before an enum can be used, a variable needs to be declared:

enum islamic_months months;

ISLAMIC_CAL months;

Page 18: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

There are cases where it is appropriate for us to use an enum. This is an example of such a case:

enum islamic_months months;

GetMonth(&months);

switch(months) {

case muharam:

. . .

break;

case safar:

. . .

break;

. . .

}

Page 19: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

This is another case where it is appropriate to use an enum:

enum Boolean {FALSE, TRUE};

void main(void) {

int list[], target;

enum Boolean found;

Read(list);

scanf(“%d”, &target);

found = Search(list, target);

if (found == TRUE)

printf(“FOUND!!”);

else

printf(“Cannot find the requested item”);

}

Page 20: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

#include <stdio.h>

typedef enum months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC} MONTH;

void main(void) {MONTH month;char *monthsName[12] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”};

for (month = JAN; month <= DEC; month++)printf(“%s %s”, month, monthsName[month-1]);

}

Output: JAN JanuaryFEB FebruaryMAR Marchetc

Page 21: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Unions

A union allows you to handle an area of memory that could contain different types of variables. The syntax for unions is identical to that for structures. You can use either typedef's or instream definitions: simply replace the word struct with the word union.

You can contain unions within structures, or structures within unions. Either way, the C union is an unwieldy mechanism.

A union might be used to group different record layouts from the same file, or to handle a single field that could contain, for example, either numeric or character data.

Page 22: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Unions

Exampletypedef struct transaction{

int      amount;    union    {      int    count;      char   name[4];      } udata;    char     discount; } Transaction;

Page 23: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Unions

The fields in this structure are referred to as follows:

Transaction trans;

trans.amount = 0;trans.udata.count = 0;trans.discount = 'N'; //trans.udata.name = “ali”;

Just as in any other language, it's up to you to determine what kind of variable is present in any instance.

Page 24: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Unions

Using Structures within Unions:Unions can contain any types of variables, including structures. Be aware that the length of a union is the length of its longest variable. If the name in the previous example had only been 3 characters long, there would have been an undefined slack byte after name, since an integer occupies 4 bytes.

If you have a more complex situation than a simple redefine of one scalar variable with another, you may need to use structures in the union. Let's say an area in the record could contain either one long integer or two short integers; one solution would be to define a structure for the two shorts.

Page 25: Structures and Enumerations Introduction Structure definitions Nested structure Referring and initializing structure elements Passing structures to a function

Unions

typedef struct twoshorts   {   short smallamount1;   short smallamount2;   } TwoShorts;

typedef union udata   {   TwoShorts smallamounts;   int       bigamount;   } Udata;