Docsity

Struct, Typedef, Union, Enum - Programming Using C | CGS 3460, Study notes of Computer Science

Partial preview of the text

Download Struct, Typedef, Union, Enum - Programming Using C | CGS 3460 and more Study notes Computer Science in PDF only on Docsity!

struct, typedef,union, enumCGS 3460, Lecture 35Apr 7, 2006Hen-I Yang

Previously… „^ Strings

Result of Quiz 4 „^ Average: 60.1 „^ Max: 93, Min: 6 „^ 71.6% get 90% or more

Grading Scale: Hw_Quiz 4 „^ >70: 100% of the grade forhomework „^ 50 -- 69: 90% of the gradefor homework „^ 40 -- 49: 80% of the gradefor homework „^ 30 -- 39: 60% of the gradefor the homework „^ 39 or below: at most 60% ofthe grade for the homework

20 18 16 14 12 10 8 6 4 2 0 >^

80^ > ^

50^ <=

By Popular Demand „^ Sample Code „^ Sample Code for Strings

Structure variable „^ Compared to Array:^

^

Array: all elements have the

same type

, we

specify the

subscript

to pick the element we

want Structure: elements (members) can be of different types

, each member has a

name

Struct example^ struct

int item_no; char

name[8]; float

price; float

discount; float

tax; }^ item1,

item2;

Operation on struct^ printf(“The

price

of^

%s^ is

%f\n”,

item1.name,

item1.price);

printf(“The

price

of^

%s”^

has

gone

up by

dollar.\n”);

item1.price

printf(“The

new

price

of^

%s^ is

%f\n”,

item1.name,

item1.price);

Operation on struct (II) „^ We can use scanf to fill in the value of membertoo. „^ We can use = for assignment^ item2 = item1;^

^

remember array cannot allocate memory, copy the values of the membersone by one „^ = only works for structures of compatible types(of the same type), more about this later „^ != and == and other operators do not work onstructures

Structure tag struct

item

{ int item_no;char name[8];float price;float discount;float tax; } ; struct item item1 =

{101, “gum”, 1.00, 0.25, 0.07}; struct item item2;item2 = item1;

Define a new type with struct typedef

struct

int item_no; char

name[8]; float

price; float

discount; float

tax; }^ Item;

Nested Array and Struct „^ Arrays may have structures as their elements^

^

Item grocery[10]; (where Item is a newly defined type) struct item inventory[100]; Inventory[3].price = 4.95; „^ Structures may contain arrays and structures asmembers^ ^

Item.name in the previous example „^ Initializing an array of structures^ ^

Const struct dialing_code country_codes[] ={{“Argentina”, 54}, {“Bangladesh”,880}, …..{“UnitedState”, 1 }};

Summary „^ Sample Code „^ Struct „^ Typedef