Top Banner
Morteza Noferesti
28

Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

Aug 21, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

Morteza Noferesti

Page 2: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

2

The C language provides a facility called typedef for creatingsynonyms for previously defined data type names.

For example, the declaration:

typedef int Length;

Length a, b, len ;

Length numbers[10] ;

makes the name Length a synonym (or alias) for the data type int.

The data type name Length can now be used in declarations in exactlythe same way that the data type int can be used:

typedef char String[50];

typedef int Array[10];

String name;

Array ages;

Page 3: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

3

Structures—sometimes referred to as aggregates—are collections ofrelated variables under one name

Structures may contain variables of many different data types—incontrast to arrays that contain only elements of the same data type

Structures are commonly used to define records

Pointers and structures facilitate the formation of more complexdata structures such as linked lists, queues, stacks and trees

Structures are derived data types—they are constructed using objectsof other types

Page 4: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

4

struct employee

{char firstName[ 20 ];char lastName[ 20 ];int age;char gender;double hourlySalary;

} Ali, Sara, empDTS[20];

struct employee

{

char firstName[ 20 ];

char lastName[ 20 ];

int age;

char gender;

double hourlySalary;

};

The name "employee" is called a structure tag

Page 5: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

5

Members of the same structure type must have uniquenames, but two different structure types may containmembers of the same name without conflict

Each structure definition must end with a semicolon

struct employee

{char Name[ 20 ];char Name[ 20 ]; // Error!!!int age;char gender;double hourlySalary;

} Ali, Sara, empDTS[20];

struct employee Reza, *emp;

struct Student

{char Name[ 20 ]; // OKint age;char gender;

};

struct Student Ce40153[80];

Page 6: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

6

A structure cannot contain an instance of itself

For example, a variable of type struct employee cannot bedeclared in the definition for struct employee A pointer to structemployee, however, may be included

A structure containing a member that is a pointer to the samestructure type is referred to as a self-referential structure

struct employee {

// …

double hourlySalary;

struct employee person; /* ERROR */

struct employee *ePtr; /* pointer */

};

Page 7: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

7

The structure tag name is optional

If a structure definition does not contain a structure tagname, variables of the structure type may be declaredonly in the structure definition—not in a separatedeclaration

struct

{char firstName[ 20 ];char lastName[ 20 ];int age;char gender;double hourlySalary;

} Ali;

Page 8: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

8

Structure definitions do not

reserve any space in memory;

rather, each definition creates a

new data type that is used to

define variables

sizeof(struct …) =

sum of sizeof(members) +

alignment padding

(Processor- and compiler-specific)

struct employee

{

char firstName[ 20 ];

char lastName[ 20 ];

int age;

char gender;

double hourlySalary;

};

struct employee Ali, emp[10];

printf("%d", sizeof(Ali));

printf("%d", sizeof(emp));

printf("%d", sizeof(struct

employee));

Page 9: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

9

it's much, much easier on the processor if the

compiler arranges it like this:

most compilers will “pad” the structure (as if

with extra, invisible fields) like this:

struct {

char a[3];

short int b;

long int c;

char d[3];

};

Page 10: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

10

Individual members of a struct variable may be accessed

using the structure member operator (the dot, "."):

myEmp.firstName ;

employee. firstName; // Error

Or , if a pointer to the struct has been declared and

initialized

employee *emp = &myEmp ;

◦ by using the structure pointer operator :

emp→firstName; // arrow operator

◦ which could also be written as:

(* emp).firstName;

Page 11: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

11

personageLastNameFirstName

gpaid

20914015314Jafarinezhadomidstudents[0]

20222222290ShekarestaniSamadStudents[1]

2011111111100ShekarestaniKhaje Nezamstudents[2]

students[3]

struct identity sharifC40153[80] = {“Omid", "Jafarinezhad", 14, 9140153, 20,

"Samad", "Shekarestani", 90, 2222222, 20} ;

strcpy(sharifC40153[2].FirstName, "Khaje Nezam");

strcpy(sharifC40153[2].LastName, "Shekarestani");

sharifC40153[2]. age = 100;

sharifC40153[2]. person.id = 11111111;

sharifC40153[2]. person. gpa = 20;

Page 12: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

12

bool check_birthday(struct Date today, struct Date myFriend)

{

if ((today.month == myFriend.month) &&

(today.day == myFriend.day))

return (true);

return (false);

}

int main()

{

struct Friend friends[NFRIENDS];

struct Date today = {2017, 11, 25};

// ...

for (i = 0; i < NFRIENDS; i++)

{

if(check_birthday(today, friends[i].Birthday))

printf ("%s %s\n", friends[i].FirstName, oj.LastName) ;

} // …

#define NFRIENDS 10

struct Date

{

unsigned year;

unsigned month;

unsigned day;

};

struct Friend

{

char FirstName[30];

char LastName[30];

struct Date Birthday;

};

Page 13: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

13

…8 bit …

…8 bit …

…8 bit …

Notice that bit field members of structures are accessedexactly as any other structure member

Padded to be an integral number of words◦ Placement is compiler-specific

struct Flags

{

int f1:3;

unsigned int f2:1;

unsigned int f3:2;

} foo;

foo.f1 = -2;

foo.f2 = 1;

foo.f3 = 2;

1 1 0 1 1 0 … …

f1 f2 f3

Page 14: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

14

Date create_date1(int month,

int day,

int year)

{

Date d;

d.month = month;

d.day = day;

d.year = year;

return (d);

}

void create_date2(Date *d,

int month,

int day,

int year)

{

d->month = month;

d->day = day;

d->year = year;

}

Date today;

today = create_date1(9, 4, 2008);

create_date2(&today, 9, 4, 2008);

Page 15: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

15

typedef struct

{

char firstName[ 20 ];

char lastName[ 20 ];

int age;

char gender;

double hourlySalary;

} employee; /* The "alias"

employee Ali; /* Create a struct variable */

Page 16: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

16

Structures may not be compared using operators ==

and !=

struct a {

int a; int b;

};

struct a b, c;

b.a = 10;

b.b = 30;

c = b;

if(c == b) // Error

Page 17: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

17

Enumeration is a user-defined data type. It is defined using

the keyword enum and the syntax is:

enum tag_name {name_0, …, name_n} ;

The tag_name is not used directly. The names in the braces

are symbolic constants that take on integer values from zero

through n. As an example, the statement:

enum colors { red, yellow, green } ;

◦ creates three constants. red is assigned the value 0, yellow is assigned 1

and green is assigned 2

Page 18: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

18

#include <stdio.h>

int main( )

{

int March[5][7]={{0,0,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,0,0}};

enum days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

enum week {week_one, week_two, week_three, week_four, week_five};

printf ("Monday the third week of March is March %d\n",

March [week_three] [Monday] );

}

Page 19: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

19

Values in an enum start with 0, unless specified otherwise, and are

incremented by 1

The identifiers in an enumeration must be unique

Multiple members of an enumeration can have the sameconstant value

Assigning a value to an enumeration constant after it has beendefined is a syntax error

Use only uppercase letters enumeration constant names. This makesthese constants stand out in a program and reminds you thatenumeration constants are not variables

Page 20: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

20

enum months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT,

NOV, DEC };

enum months month;

/* initialize array of pointers */

const char *monthName[] = { "", "January", "February", "March",

"April", "May", "June", "July", "August", "September", "October",

“November", "December"};

for (month = JAN; month <= DEC; month++ )

{

printf( "%2d%11s\n", month, monthName[month] );

}

Page 21: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

21

A union is a derived data type—like a structure—withmembers that share the same storage space

For different situations in a program, some variablesmay not be relevant, but other variables are—so aunion shares the space instead of wasting storage onvariables that are not being used

The members of a union can be of any data type

The number of bytes used to store a union must be atleast enough to hold the largest member

Only one member, and thus one data type, can bereferenced at a time

Page 22: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

22

union myDataUnion {

int i;

char c;

float f;

} u1, u2;

union myDataUnion u3;

u1.i = 4;

u1.c = ’a’;

u2.i = 0xDEADBEEF;

c

i

f

Page 23: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

23

In a declaration, a union may be initialized with a value

of the same type as the first union member

union a

{

int c; // OK

char b[4];

};

union a test;

test.c = 10;

printf("%d", test.c);

Page 24: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

24

A union value doesn’t "know" which case it contains

union AnElt {

int i;

char c;

} elt1, elt2;

elt1.i = 4;

elt2.c = ’a’;

elt2.i = 0xDEADBEEF;

if (elt1 currently has a char) …

How should your program keep track whether

elt1, elt2 hold an int or a char?

Basic answer: Another variable holds that info

Page 25: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

25

enum Union_Tag {IS_INT, IS_CHAR};

struct TaggedUnion {

enum Union_Tag tag;

union {

int i;

char c;

} data;

};

Tag every value with its case

Page 26: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

26

Page 27: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

27

class GradeBook

{

public:void setCourseName( string name )

{

courseName = name; }

string getCourseName()

{

return courseName;

}void displayMessage()

{

cout << "Welcome to the grade book for\n" << getCourseName()

<< "!" << endl;

}

private:string courseName;

};

Page 28: Morteza Noferesti - ce.sharif.educe.sharif.edu/courses/96-97/1/ce153-6/resources/root/Slides/Structur… · 2 The C language provides a facility called typedef for creating synonyms

28

GradeBook book(“MyBook”);

int number;

cin >> number;

cout << “Book ” << book.getCourseName()<< “ has ” << number << “ pages”

<< endl;