Structured Data Objects (Structs)

23
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Struc ts Structured Data Objects (Structs) Chapter 7

description

Structured Data Objects (Structs). Chapter 7. Structs (structured data objects). Recall our definition of an array : • an array is a fixed number of contiguous storage elements all of the same data type . • The abstract data type struct avoids one restriction:. - PowerPoint PPT Presentation

Transcript of Structured Data Objects (Structs)

Page 1: Structured Data Objects (Structs)

Page 1

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

Structured Data Objects(Structs)

Chapter 7

Page 2: Structured Data Objects (Structs)

Page 2

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

Recall our definition of an arrayarray:• an array is a fixedfixed number of contiguouscontiguous storage elements allall

of the same data typeof the same data type. • The abstract data type structstruct avoids one restriction:

• The elements be NEED NOTNEED NOT all be of the same data type.

Structs Structs (structured data objects)(structured data objects)

A structstruct:

• Consists of 2 or more component data types• A component part may be either a simple data type

(e.g., intint, unsigned intunsigned int, floatfloat, charchar, longlong, doubledouble, etc.)A pointer

(e.g., * intint, * floatfloat, * charchar, * longlong, * doubledouble, etc.)

Or another structured object (i.e., abstract type structstruct)

Page 3: Structured Data Objects (Structs)

Page 3

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

A structstruct corresponds to records in a database• Assume we maintain a simple database of student information

Attribute (Field)Attribute (Field) Data TypeData TypeStudent Name String (Allow for 30 characters)Student ID Integer (int)Major String (Allow for 10 characters)Grade-Point Average Real (floatfloat)Hours Completed Integer (int)

This record (let’s call it studentstudent):• Consists of 5 (five) data elements

• Consists of 3 (three) different data types

(Student Name, Student ID, Major, Grade-Point Average, Hours Completed)

(Strings (2), Integers (2), and a real (floatfloat))

Page 4: Structured Data Objects (Structs)

Page 4

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

Declaring Records (in other languages):COBOL: 01 STUDENT

02 STUDENT-NAME PIC X(30).02 STUDENT-ID PIC 9(6).02 MAJOR PIC X(10).02 GPA PIC 9V99.02 TOTAL-HOURS PIC 999.

Pascal: type student = record student_name : array[1..30] of char; student_id : integer; major: array[1..10] of char; gpa: real;. total_hours : integer;

end;

SQL: create table student ( student_name char(30) not null,

student_id integer not null, major char(10) default ‘CIS’, gpa decimal(4,2), total_hours smallint,

primary key (student_id), check (gpa > 0) )

Page 5: Structured Data Objects (Structs)

Page 5

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

Declaring Records (in C):

struct student{ char student_name[31]; // Remember: we need 1-byte for ‘\0’ int student_id; char major[11]; // Remember: we need 1-byte for ‘\0’ float gpa; int total_hrs; };

We have created a new data type: struct student struct student • just as with basic data types, we can now associate variables

(specific locations in RAM) with the data type struct studentstruct student• just as with basic data types, whenever we declare a variable

to be of type struct studentstruct student, we are requesting a specific number of contiguous bytes of RAM storage.

How many bytes of storage do we need for a How many bytes of storage do we need for a structstruct??

That depends on the struct

Page 6: Structured Data Objects (Structs)

Page 6

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

For our struct (struct student):

ElementElement BytesBytescharchar student_name[31]; 31intint student_id; 2charchar major[11]; 11floatfloat gpa; 4intint total_hrs; 2

50

We need 5050 bytes of contiguous RAM storage for our data type struct studentstruct student

How do we declare and use How do we declare and use structsstructs in a C program ?? in a C program ??

Page 7: Structured Data Objects (Structs)

Page 7

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

Consider the following program:#include <stdio.h> struct student{ char student_name[31]; int student_id; char major[11]; float gpa; int total_hrs; }; int main(){ struct student active = {"Favre, Brett",12345,"CIS",3.27,67}; struct student alumni = {"White, Reggie", 23456, "Pain", 1.34, 89};

printf("Name: %13s %14s\n",active.student_name, alumni.student_name); printf("ID: %13d %14d\n",active.student_id, alumni.student_id); printf("Major: %13s %14s\n",active.major, alumni.major); printf("gpa: %13.3f %14.3f\n",active.gpa, alumni.gpa); printf("Hours: %13d %14d\n",active.total_hrs, alumni.total_hrs); return 0;}

Page 8: Structured Data Objects (Structs)

Page 8

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

How is this data stored in RAM??How is this data stored in RAM??

As with ALL data types, the data type structstruct has a base address:• assume that variable activeactive (of data type struct studentstruct student) has the

base address 7520 (and requiring 50 contiguous bytes, to 7569)

7520

F7521

a7522

v7523

r7524

e7525

,7526 7527

B7528

r7529

e7530

t7531

t7532

\07533

--7534

--7535

--7536

--7537

--7538

--7539

--7540

--7541

--7542

--7543

--7544

--7545

--7546

--7547

--7548

--7549

--7550

--7564

7561

--7552

12345

7553

C7554

I7555

S7556

\07557

--7558

--7559

--7560

--7562

--7563

--

7551

7565

756875677566

3.27

7569

67

Page 9: Structured Data Objects (Structs)

Page 9

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

How can the address of each element in the How can the address of each element in the structstruct be be calculated??calculated??

Just as we calculated the address of each element in an array, the address of each element in a struct struct is determined by adding the amount of storage required for each element and adding it to the base address.

Element Start addr. Storage Next Address

student_name 7520 31-bytes 7520 + 31 = 7551student_ID 7551 2-bytes 7551 + 2 = 7553

majorOr: 7520 + 33 = 7553

7553 11-bytes 7553 + 11 = 7564

gpa 7564 4-bytesOr: 7520 + 44 = 7564

7564 + 4 = 7568Or: 7520 + 48 = 7568

total_hrs 7568 2-bytes N/A

Type

char [31]int

char [11]

float

int

Page 10: Structured Data Objects (Structs)

Page 10

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

BUTBUT, if , if structs structs are equivalent to records in a database, how are equivalent to records in a database, how can a database consist of only one (1) record ???can a database consist of only one (1) record ???

We can have an array of structstruct, just as we can have an array of intint, and array of floatfloat, an array of charchar (string), etc.• Remember: a structstruct, while abstract, is simply a data type

struct student{ char student_name[20]; // names no longer than 19 characters float gpa; };

For the sake of simplicity, let’s assume the following record structure:

How would this How would this structstruct be set up as an array ??? be set up as an array ???

Page 11: Structured Data Objects (Structs)

Page 11

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

Consider the following code:#include <stdio.h>struct student{ char student_name[20]; float gpa; }; int main() { struct student active[5] = {{"Favre, Brett",3.26}, {"White, Reggie",1.34}, {"Smith, Bruce",3.78}, {"Smith, Emmitt", 2.05}, {"Rice, Jerry", 3.55}}; int i; for (i = 0; i < 5; i++) printf("Name: %15s gpa: %4.2f\n", active[i].student_name,active[i].gpa); return 0;}

Page 12: Structured Data Objects (Structs)

Page 12

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

The program, as entered, produces the output:

Name: Favre, Brett gpa: 3.26Name: White, Reggie gpa: 1.34Name: Smith, Bruce gpa: 3.78Name: Smith, Emmitt gpa: 2.05Name: Rice, Jerry gpa: 3.55

How does this program work ?? What if we were searching How does this program work ?? What if we were searching for a specific name, …. Say, for a specific name, …. Say, Bruce SmithBruce Smith ??? ???

Consider the following C code

Page 13: Structured Data Objects (Structs)

Page 13

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

#include <stdio.h> #include <string.h>struct student { char student_name[20]; float gpa; }; int main(){ struct student active[5] = {{"Favre, Brett",3.26}, {"White, Reggie",1.34}, {"Smith, Bruce",3.78}, {"Smith, Emmitt",2.05}, {"Rice, Jerry",3.55}}; int i = 0; char find[20] = "Smith, Bruce"; while((strcmp(active[i].student_name,find)!=0)&&(i<5)) i++; if (i >= 5) printf("The name is NOT on the list"); else printf("%s IS on the list (gpa = %4.2f)", active[i].student_name, active[i].gpa); return 0;}

Page 14: Structured Data Objects (Structs)

Page 14

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

structsstructs and pointersstructsstructs, like any other data type, have base addresses, and can be accessed by referring to its address.

Consider the following modification of our previous program:

#include <stdio.h> struct student { char name[18]; float gpa; };int main(){ struct student active[5] = {{"Favre, Brett",3.26}, {"White, Reggie",1.34}, {"Smith, Bruce",3.78}, {"Smith, Emmitt",2.05}, {"Rice, Jerry",3.55}}; struct student *record = active; printf(“%lu\n”, &record); while(record <= &active[4]) { printf(“%lu %20s %7.3f\n”, record, record->name, record->gpa); record++; {return 0;}

Page 15: Structured Data Objects (Structs)

Page 15

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

The following output would be produced:

8671286562��������Favre, Brett��3.26086584�������White, Reggie��1.34086606��������Smith, Bruce��3.78086628�������Smith, Emmitt��2.05086650���������Rice, Jerry��3.550

Note: These addresses are not the TRUE addresses, and they may change with each run

How does this program work ??How does this program work ??

Page 16: Structured Data Objects (Structs)

Page 16

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

Let’s take it from the line:

struct student * record = active;

Our new data type

struct student { char name[18]; float gpa; };

pointer to

The BASEBASE addressof our arrayarray activeactive

The same as: &active[0]&active[0]

Meaning, the variable pointer recordrecord is now initialized to the BASE address of array activeactive ( or, in or case, 8656286562)

How would this appear in RAM??How would this appear in RAM??

Page 17: Structured Data Objects (Structs)

Page 17

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

86562

F86563

a86564

v86565

r86566

e86567

,86568 86569

B86570

r86571

e86572

t86573

t86574

\086577

--86578

--86579

--86581

3.2686582 86583

86584

W86586

h86586

i86587

t86589

,86593

g86595

i8660386596

e

The contents of address recordrecord ( = active active OR &active[0]&active[0])Points to

86575

--86576

--86580 86590 86591

R86592

e86594

g86597

\086598

--86599

--

86588

e86602 86604

1.34

86605

Continue to

86650

R86651

i86652

c86653

e86654

,86655 86656

J86657

e86658

r86659

r86660

y86661

\086662

--86663

--86664

--86665

--86666

--

86600

--86601

--

86667

--86668 86669

3.5586670 86671

86712 86713

8656286714 86715

Located at

Page 18: Structured Data Objects (Structs)

Page 18

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

The next statement in the program: printf(“%lu\n”, &record);

Prints the BASE ADDRESS of our structure 86712 86713

8656286714 86715

NOTNOT the contents

(Which contains the base address of our array activeactive)

Notice also that ALL pointers (e.g., recordrecord) require 4-bytes of storage

We can now begin our loop:

while(record <= &active[4])

recordrecord CONTAINS the address

86712 86713

8656286714 86715

Which is less than the base address of our 5th record (86650)

Enter Loop

Page 19: Structured Data Objects (Structs)

Page 19

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

Now we simply print out the first record:printf(“%lu %20s %7.3f\n”, record, record->name, record->gpa);

The CONTENTS of recordrecord

Field: namename (on 20 spaces)

Field: gpagpa (as f7.3)

86562��������Favre, Brett ��3.260

An alternative statement is: (*record).name(*record).name

Notice that the statement record->namerecord->name is a REDIRECT:• Go to the ADDRESS contained in record and find field name • i.e., recordrecord contains the address 86562, and namename is at 86562 • The redirect record->gparecord->gpa would yield the address 86580

Page 20: Structured Data Objects (Structs)

Page 20

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

The next statement: record++;record++;

Increments the contents of recordrecord:

86712 86713

8656286714 86715

Changed to:

86712 86713

8658486714 86715

The contents of recordrecord are increased by 22

Why are the contents increased by 22 and not 1 ???Why are the contents increased by 22 and not 1 ???

Record is pointer to our data type struct student (Initialized as: struct student *record;) which requires 22-bytes of storage. Incrementing increases the value contained by 22. Decrementing it (i.e., record --;record --; or --record;--record; would decrease the value contained by 22)

Page 21: Structured Data Objects (Structs)

Page 21

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

Remember:

int *integer_pointer; // contains an address to an integerfloat *float_pointer; // contains an address to a floatdouble *double_pointer; // contains an address to a double

IF:IF: Variable Located at Containsinteger_pointer 12345 46788float_pointer 12349 22734double_pointer 12353 71122

• A pointer is an address in RAM which contains an address• What type of data is at that address MUST be known in advance

Then:Then: Statement Will result in the new value

integer_pointer++; 46790++float_pointer; 22738double_pointer--; 71114

Page 22: Structured Data Objects (Structs)

Page 22

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs

For the rest of the loop:

recordrecord value Output

86584�������White, Reggie��1.34086584

86606��������Smith, Bruce��3.78086606

86628�������Smith, Emmitt��2.05086628

86650���������Rice, Jerry��3.55086650

86672

Greater than

Stop

Page 23: Structured Data Objects (Structs)

Page 23

Data Structures in C for Non-Computer Science Majors

Kirs and Pflughoeft

Structs