26
Structures in C Programming ESC 151 Sunnie Chung

Structures in C Programming - csuohio.edueecs.csuohio.edu/.../ESC151LectureNotes_Structures.pdf · Data Structures: Data Structures: StructStruct • A Structure is a collection of

Embed Size (px)

Citation preview

Structures in C Programming

ESC 151

Sunnie Chung

Data Structures: Data Structures: Data Structures: Data Structures: StructStructStructStruct

• A Structure is a collection of related data items, possibly of different

types.

• A structure type in C/C++ is called Struct.

• A Struct is heterogeneous in that it can be composed of data of

different types.

• In contrast, array is homogeneous since it can contain only data of the

same type.

ESC 151 C Programming Sunnie Chung 2

Data Structures: Data Structures: Data Structures: Data Structures: StructsStructsStructsStructs

• Arrays require that all elements be of the same data type.

• Many times it is necessary to group information of different data types.

• An example is a materials list for a product. The list typically includes a name for each item, a part number, dimensions, weight, and cost.

• C and C++ support data structures that can store combinations of character, integer floating point and enumerated type data. They are called a structs.

ESC 151 C Programming Sunnie Chung 3

4

StructuresStructuresStructuresStructures

• Structures hold data that belong together.

• Examples:

• Student record: id, name, major, gender, start year, gpa

• Bank account: account number, name, currency, balance

• Address book: name, address, telephone number

• In database applications, structures are called records.

Different types of data in each Different types of data in each Different types of data in each Different types of data in each rrrrow structure ow structure ow structure ow structure in Table Employee in Table Employee in Table Employee in Table Employee

ID Name DeptID Salary Project

10 Nemo 12 22000 Company Picnic

20 Dory 156 79000 Big data Project

40 Gill 89 76000 Factory Sensor Project

52 Ray 34 85000 Cloud Project

… … … … …

Employee

Structures: Structures: Structures: Structures: structstructstructstruct

• A struct is a derived data type composed of members that are each primitive or derived data types.

• A single struct would store the data for one object.

• An array of structs would store the data for several objects.

• A struct can be defined in several ways as illustrated in the following examples:

ESC 151 C Programming Sunnie Chung 6

Declaring Declaring Declaring Declaring Structures Structures Structures Structures ((((structstructstructstruct))))

Does Not Reserve Memory Space

struct my_example

{

int label;

char letter;

char name[20];

} ;

/* The name "my_example" is called a

structure tag */

Reserves Memory Space

struct my_example{

int label;char letter;char name[20];

} mystruct ;/*Declaring a struct variable mystruct*/

ESC 151 C Programming Sunnie Chung 7

User Defined Data Types (User Defined Data Types (User Defined Data Types (User Defined Data Types (typedeftypedeftypedeftypedef))))

• The C language provides a facility called typedef for creating synonyms for previously defined data type names. For example, the declaration:

typedef int Length;

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 exactly the same way that the data type int can be used:

Length a, b, len ;

Length numbers[10] ;

ESC 151 C Programming Sunnie Chung 8

Declaring with Declaring with Declaring with Declaring with TypedefTypedefTypedefTypedef & & & & StructStructStructStruct : better way: better way: better way: better way

• Often, typedef is used in combination with struct to declare a synonym (or an alias) for a structure:

typedef struct /* Define a structure */

{

int label ;

char letter;

char name[20] ;

} Some_name ; /* The "alias" Some_name is the name of struct type*/

Some_name mystruct ; /* Declare a struct type variable mystruct */

ESC 151 C Programming Sunnie Chung 9

Accessing Accessing Accessing Accessing StructStructStructStruct MembersMembersMembersMembers

• Individual members of a struct variable may be accessed using the structure member operator (the “.” dot):

mystruct.label = 1011;

mystruct.letter = ‘A’ ;

strcpy(mystruct.name, "Mark");

• Or if a pointer to the struct has been declared and initialized

Some_name *myptr = &mystruct ;

by using the structure pointer operator (the “->“):

myptr -> letter ;

which could also be written as:

(*myptr).letter ;

ESC 151 C Programming Sunnie Chung 10

Initializing Initializing Initializing Initializing StructStructStructStruct

struct personal //Create a struct but don’t reserve memory space.

{

long id;

double gpa;

};

typedef struct //Create another struct that includes the first struct. No memory allocated yet

{

char name[30];

struct personal person;

}Student;

Student js = { "Joe Smith", { 0, 0.0 } };

strcpy(js.name, "Mark Smith");

js.person.id = 123456789;

js.person.gpa = 3.4;

ESC 151 C Programming Sunnie Chung 11

Initializing Initializing Initializing Initializing StructStructStructStruct

Student js = {"Joe Smith"}; //memory for Student type js allocated here

Student *jsptr = &js ; // pointer to Strudent type is allocated and

// initialized to the address of js

js.person.id = 123456789 ;

js.person.gpa = 3.4 ;

printf ("%s %ld %f\n", js.name, js.person.id, js.person.gpa) ;

printf ("%s %ld %f\n", jsptr->name, jsptr->person.id,

jsptr->person.gpa) ;

ESC 151 C Programming Sunnie Chung 12

Initializing Initializing Initializing Initializing Array of Array of Array of Array of StructStructStructStruct

Studentlist[2];

//get the first student info

strcpy_s(list[0].name, _countof(list[0].name), "Mark Juckerberg");

list[0].person.id = 111111111;

list[0].person.gpa = 3.0;

// print array of struct

int j;

int count;

for(j = 0; j < count; j++) {

printf("%s %ld %f\n", list[j].name, list[j].person.id, list[j].person.gpa);

}

ESC 151 C Programming Sunnie Chung 13

How to Pass How to Pass How to Pass How to Pass StructStructStructStruct to a Functionto a Functionto a Functionto a Functionstruct inventory{

int nPartNo;

float fBuyCost;

float fSellingPrice;

};

-- Function Prototypes

struct inventory ReadPart(void);

void PrintPart(struct inventory part);

-- in main () to call the Functions

struct inventory items;// call ReadPart() function, assigns returned structure to items

items = ReadPart();// then, call PrintPart() function, passing items structure

PrintPart(items);

ESC 151 C Programming Sunnie Chung 14

How to Pass How to Pass How to Pass How to Pass StructStructStructStruct to a Functionto a Functionto a Functionto a Function-- Function Prototypes

void Print_Student_withStruct(Student s);

void Print_Student_withPointer(Student* ptr);

void Print_All_Students(Student List[], int number);

-- in main () to call the Functions

Student js = { "Joe Smith", { 111111111, 3.0 } };

Student *jsptr = &js; //Declaring a pointer to Struct variable js

Print_Student_withStruct(js);

Print_Student_withPointer(jsptr);

Student allstudents[2]; //Declaring Array of Struct variable

int count = 2;

Print_All_Students(allstudents, count);

ESC 151 C Programming Sunnie Chung 15

Sample Program with Sample Program with Sample Program with Sample Program with StructsStructsStructsStructs

/* This program illustrates creating structs and then declaring and using struct variables. *

* Note that struct personal is an included data type in struct “Student". */

struct personal //Create a struct but don’t reserve memory space.

{

long id;

double gpa;

};

typedef struct //Create a second struct that includes the first struct. No memory allocated yet

{

char name[30];

struct personal person;

}Student;

ESC 151 C Programming Sunnie Chung 16

Sample Program with Sample Program with Sample Program with Sample Program with StructsStructsStructsStructs (cont.)(cont.)(cont.)(cont.)

int main ( )

{

struct identity js = {"Joe Smith"}; //memory for struct allocated here

struct identity *jsptr = &js ;

js.person.id = 123456789 ;

js.person.gpa = 3.4 ;

printf ("%s %ld %f\n", js.name, js.person.id, js.person.gpa) ;

printf ("%s %ld %f\n", jsptr->name, jsptr->person.id, jsptr->person.gpa) ;

}

ESC 151 C Programming Sunnie Chung 17

Sample Program with Sample Program with Sample Program with Sample Program with StructsStructsStructsStructs (cont.)(cont.)(cont.)(cont.)int main ( )

{

Print_Student_withStruct(js);

Print_Student_withPointer(jsptr);

Studentallstudents[2];

int count = 2;

//First Student Info

strcpy_s(allstudents[0].name, _countof(allstudents[0].name), "Mark Juckerberg");

allstudents[0].person.id = 111111111;

allstudents[0].person.gpa = 3.0;

//Second Student Info

strcpy_s(allstudents[1].name, _countof(allstudents[1].name), "Sunnie Chung");

allstudents[1].person.id = 222222222;

allstudents[1].person.gpa = 3.5;

Print_All_Students(allstudents, count);

return 0;

}ESC 151 C Programming Sunnie Chung 18

Sample Program with Sample Program with Sample Program with Sample Program with StructsStructsStructsStructs (cont.)(cont.)(cont.)(cont.)void Print_Student_withStruct(Student s){

printf("\n\n******* Printing Student From Function with Struct******************** \n ");

printf("%s %ld %f\n", s.name, s.person.id, s.person.gpa);

}

void Print_Student_withPointer(Student* sptr){

printf("\n\n******* Printing Student From Function with Pointer of Struct********** \n ");

printf("%s %ld %f\n", sptr->name, sptr->person.id, sptr->person.gpa);

}

void Print_All_Students(Student List[], int scount){

int j;

printf("\n***** Printing All the Students **************\n");

for(j = 0; j < scount; j++) {

printf("%s %ld %f\n", List[j].name, List[j].person.id, List[j].person.gpa);

}

ESC 151 C Programming Sunnie Chung 19

StructsStructsStructsStructs with Unionwith Unionwith Unionwith Union

• The program on the next 3 slides creates a union and makes it a member of struct personal which is, in turn, a member of structidentity.

• The union uses the same memory location for either rank or a character string (deg) depending on the answer to the prompt for student status in main( ).

ESC 151 C Programming Sunnie Chung 20

StructsStructsStructsStructs with Union (cont.)with Union (cont.)with Union (cont.)with Union (cont.)

#include <stdio.h>

union status

{

int rank ;

char deg[4] ;

} ;

struct personal

{

long id ;

float gpa ;

union status level ;

} ;

struct identity

{

char name[30] ;

struct personal student ;

} ;

ESC 151 C Programming Sunnie Chung 21

StructsStructsStructsStructs with Union (cont.)with Union (cont.)with Union (cont.)with Union (cont.)

int main( )

{ struct identity jb = {"Joe Brown"}, *ptr = &jb;

char u_g;

jb.student.id = 123456789 ;

jb.student.gpa = 3.4 ;

printf ("Enter student status - u or g\n");

scanf ("%c", &u_g);

if (u_g == 'u')

{ printf ("Enter rank -- 1, 2, 3, 4 or 5\n");

scanf ("%d", &jb.student.level.rank);

printf ("%s is level %d\n” , jb.name ,

jb.student.level.rank);

} /* End of if statement */

ESC 151 C Programming Sunnie Chung 22

StructsStructsStructsStructs with Union (cont.)with Union (cont.)with Union (cont.)with Union (cont.)

else

{ printf ("Enter degree sought -- ms or phd\n");

scanf ("%s", &jb.student.level.deg);

printf ("%s is a %s candidate\n”,

jb.name , jb.student.level.deg );

} /* End of else statement */

printf ("%s %ld %f\n” , jb.name , jb.student.id ,

jb.student.gpa );

printf ("%s%ld %f\n” , ptr->name , ptr->student.id ,

ptr->student.gpa );

} /* End of program */

ESC 151 C Programming Sunnie Chung 23

EnumerationEnumerationEnumerationEnumeration

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

ESC 151 C Programming Sunnie Chung 24

EnumerationEnumerationEnumerationEnumeration

/* This program uses enumerated data types to

access the elements of an array */

#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};

ESC 151 C Programming Sunnie Chung 25

EnumerationEnumerationEnumerationEnumeration

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] );

}

ESC 151 C Programming Sunnie Chung 26