34
204216 -- C Programming Chapter 13 Self Reference Structure & Compiler Directive Adapted/Assembled for 204216 by Areerat T rongratsameethong A First Book of ANSI C, Fourth Edition

204216 -- C Programming · 204216 -- C Programming. Chapter 13. Self Reference Structure & Compiler Directive. Adapted/Assembled for 204216 by Areerat Trongratsameethong. A First

Embed Size (px)

Citation preview

204216 -- C Programming

Chapter 13Self Reference Structure

&Compiler Directive

Adapted/Assembled for 204216 by Areerat Trongratsameethong

A First Book of ANSI C, Fourth Edition

Objectives

• Introduction to Linked Lists• Dynamic Memory Allocation• Dynamically Linked Lists• Compiler Directive• Common Programming and Compiler Errors

A First Book of ANSI C, Fourth Edition 2

Introduction• Dynamic memory allocation: an alternative to fixed

memory allocation in which memory space grows or diminishes during program execution

• Dynamic memory allocation makes it unnecessary to reserve a fixed amount of memory for a scalar, array, or structure variable in advance– Also known as run-time allocation– Requests are made for allocation and release of memory

space while the program is running• Dynamic memory allocation คอ การจองพนทใน memory

และการคน memory ระหวางท execute โปรแกรม ชวยใหไมตองจองพนทเผอไวลวงหนา และสามารถคนพนท memory ขณะ execute โปรแกรมได หรอ ทรจกในนาม run-time allocation

A First Book of ANSI C, Fourth Edition 3

Self-Referencing Structures• An array of structures can be used to insert and delete

ordered structures, but this is not an efficient use of memory– Better alternative: a linked list

• Linked list: set of structures, each containing at least one member whose value is the address of the next logically ordered structure in the list– Also known as self-referencing structures

• การประกาศตวแปรในรปแบบ array of struct บางครงกใช memory ไมเตมประสทธภาพ เพราะในบางครงมการเพม หรอ ลดจานวน record ระหวางท run โปรแกรม (กรณทเพม record พนททจองไวกไมพอ กรณทตองการลด record พนททจองไวกวางไมไดใชประโยชน) สงทจะชวยไดคอ linked list หรอทรจกกนในนาม self-referencing structures ซงอยในรปแบบของ pointer of struct

A First Book of ANSI C, Fourth Edition 4

Introduction to Linked Lists

A First Book of ANSI C, Fourth Edition 5

Introduction to Linked Lists (1)• A NULL acts as a sentinel or flag to indicate when the last

structure has been processed- NULL ใชสาหรบบงบอกจดสนสดของ Linked List

• In addition to an end-of-list sentinel value, we must provide a special pointer for storing the address of the first structure in the list- สาหรบ List ตวแรก pointer จะถกสรางเพอเกบ address (ทอย)

ของ Linked List ตวแรก

A First Book of ANSI C, Fourth Edition 6

Introduction to Linked Lists (2)

A First Book of ANSI C, Fourth Edition 7

สมาชกของ struct สามารถเปนขอมลชนดใดๆกได รวมทง

pointer ดงตวอยางแสดงดานลาง

A First Book of ANSI C, Fourth Edition 8

pointer

Introduction to Linked Lists (3)

A First Book of ANSI C, Fourth Edition 9

is evaluated as (t1.nextaddr)->nameit can be replaced by (*t1.nextaddr).name

Introduction to Linked Lists (4)

A First Book of ANSI C, Fourth Edition10

Introduction to Linked Lists (5)

Introduction to Linked Lists (6)

A First Book of ANSI C, Fourth Edition11

Disadvantage: exactly three structures are defined in main() by name, and storage for them is reserved at compile time

Self-Referencing Structures (11)

A First Book of ANSI C, Fourth Edition 12

can be replaced by while(!contents)

Dynamic Memory Allocation

A First Book of ANSI C, Fourth Edition 13

Dynamic Memory Allocation (2)• The malloc() and calloc() functions can

frequently be used interchangeably– The advantage of calloc() is that it initializes all

newly allocated numeric memory to 0 and character allocated memory to NULL

– We use malloc() because it is the more general purpose of the two functions

– malloc(10*sizeof(char)) or calloc(10,sizeof(char)) requests enough memory to store 10 characters

• The space allocated by malloc() comes from the computer’s heapComputer’s heap คอ พนทใน memory สวนทจองไวสาหรบการจองพนทแบบ dynamic memory allocation คอ จองพนทในขณะท run โปรแกรม (allocate at run time)

A First Book of ANSI C, Fourth Edition 14

A First Book of ANSI C, Fourth Edition 15

Dynamic Memory Allocation (3)

Dynamic Memory Allocation (4)

• malloc() is more typically used for dynamically allocating memory for structures

struct OfficeInfo *Off;/* request space for one structure */Off = (struct OfficeInfo *) malloc(sizeof(struct OfficeInfo));/* check that space was allocated */if (Off == (struct OfficeInfo*) NULL){printf("\nAllocation failed\n");exit(1);

}

A First Book of ANSI C, Fourth Edition 16

pointer points to OfficeInfo struct

Dynamically Linked Lists• Both stacks and queues are examples of linked lists in

which elements can only be added to and removed from the ends of the list

• In a dynamically linked list, this capability is extended to permit adding or deleting a structure from anywhere within the list

• Such a capability is extremely useful when structures must be kept within a specified order

A First Book of ANSI C, Fourth Edition 17

Key field

INSERT and DELETEINSERT (add a new structure into a linked list)Dynamically allocate space for a new structureIf no structures exist in the listSet the address field of the new structure to a NULLSet address in the first structure pointer to address of newly created structure

Else /* we are working with an existing list */Locate where this new structure should be placedIf this structure should be the new first structure in the list

Copy current contents of first structure pointer into address field of newly created structureSet address in the first structure pointer to address of newly created structure

ElseCopy the address in the prior structure’s address member into the address field of the newly created structureSet address of prior structure’s address member to address of newly created structure

EndIfEndIf

A First Book of ANSI C, Fourth Edition 18

INSERT and DELETE (2)

A First Book of ANSI C, Fourth Edition 19

INSERT and DELETE (3)LINEAR LOCATION for INSERTING a NEW STRUCTUREIf the key field of the new structure is less than the first structure’s key field

the new structure should be the new first structureElseWhile there are still more structures in the listCompare the new structure’s key value to each structure keyStop the comparison when the new structure key either falls between

two existing structures or belongs at the end of the existing listEndWhile

EndIf

A First Book of ANSI C, Fourth Edition 20

A First Book of ANSI C, Fourth Edition21

See Slide 24

See Slide 24

INSERT and DELETE (4)

A First Book of ANSI C, Fourth Edition 22

INSERT and DELETE (5)

A First Book of ANSI C, Fourth Edition23

INSERT and DELETE (6)

A First Book of ANSI C, Fourth Edition 24

...(code for insert() and locate() goes here)…

INSERT and DELETE (7)

INSERT and DELETE (8)

• The following sample run shows the results of these tests:Enter as many names as you wish, one per lineTo stop entering names, enter a single xEnter a name: BinstockEnter a name: ArnoldEnter a name: DuberryEnter a name: CarterEnter a name: x

The names currently in the list, in alphabeticalorder, are:ArnoldBinstockCarterDuberry

A First Book of ANSI C, Fourth Edition 25

Compiler Directive• Before the actual compilation of every C program

it is passed through a Preprocessor.• All Preprocessor directives begin with the #

symbol.– #include <stdio.h>:

This causes the C declarations which are in the stdio.h header to be included for use in your program.

– #include "other.h": This causes the C declarationswhich are in the other.h header to be included for use in your program. The other.h is user-defined headerfile.

A First Book of ANSI C, Fourth Edition 26

Compiler Directive (2)

• All Preprocessor directives begin with the # symbol.– #define: The #define directive is used to define

values or macros that are used by the preprocessor to manipulate the program source code before it is compiled.

• Define Constant:#define PI 3.143

• Define Macro:#define MAX(a,b) a>b?a:b:

A First Book of ANSI C, Fourth Edition 27

Building a C Application

28

Presenter
Presentation Notes
Preprocessing phase - The preprocessor (cpp) modifies the original C program according to directives that begin with the # character. For example, the #include <stdio.h> command in line 1 of hello.c tells the preprocessor to read the contents of the system header file stdio.h and insert it directly into the program text. The result is another C program, typically with the .i suffix. Compilation phase - The compiler (cc1) translates the text file hello.i into the text file hello.s, which contains an assembly-language program. Each statement in an assembly-language program exactly describes one low-level machine-language instruction in a standard text form. Assembly language is useful because it provides a common output language for different compilers for different high-level languages. For example, C compilers and Fortran compilers both generate output files in the same assembly language. Assembly phase - Next, the assembler (as) translates hello.s into machine- language instructions, packages them in a form known as a relocatable object program, and stores the result in the object file hello.o. The hello.o file is a binary file whose bytes encode machine language instructions rather than characters. If we were to view hello.o with a text editor, it would appear to be gibberish. Linking phase - Notice that our hello program calls the printf function, which is part of the standard C library provided by every C compiler. The printf function resides in a separate precompiled object file called printf.o, which must somehow be merged with our hello.o program. The linker (ld) handles this merging. The result is the hello file, which is an executable object file (or simply executable) that is ready to be loaded into memory and executed by the system.

Common Programming Errors

• Not checking the return codes provided by malloc() and realloc()

• Not correctly updating all relevant pointer addresses when adding or removing structures from dynamically created stacks, queues, and linked lists

• Forgetting to free previously allocated memory space when the space is no longer needed

A First Book of ANSI C, Fourth Edition 29

Common Programming Errors (2)

• Not preserving the integrity of the addresses contained in the list pointer when dealing with dynamically linked list.

• Related to the previous error is the equally disastrous one of not correctly updating internal structure pointers when inserting and removing structures from a dynamically linked list

A First Book of ANSI C, Fourth Edition 30

Common Compiler Errors

A First Book of ANSI C, Fourth Edition 31

Common Compiler Errors (2)

A First Book of ANSI C, Fourth Edition 32

Summary• An alternative to fixed memory allocation for variables at

compile time is the dynamic allocation of memory at run time• malloc() reserves a requested number of bytes and

returns a pointer to the first reserved byte• realloc() operates in a similar fashion as malloc()

except it is used to expand or contract an existing allocated space

• free() is used to deallocate previously allocated memory space

• A dynamically linked list consists of structures that can be added or removed from any position in the list

• Directives are handled by the preprocessor, which is either a separate program invoked by the compiler or part of the compiler itself.

A First Book of ANSI C, Fourth Edition 33

Practice• ใหออกแบบ Function ภาษา C สาหรบรบขอมลการขายในแตละเดอน ของพนกงานขาย

แตละคน โดยมรายละเอยดขอมลดงตอไปน รหสพนกงาน ชอพนกงาน ยอดขาย คาคอมมสชน

(commission)• ใหออกแบบ Function ภาษา C เพอจดเรยงขอมลพนกงานขายโดยทเรยงตามคา

Commission จากมากไปหานอย

A First Book of ANSI C, Fourth Edition 34

พนกงานขายคนท 1

{ รหสพนกงาน: 100

ชอพนกงาน: Mr. John Smith

ยอดขาย: 1,285,050.00

Commission: 43,252.50

}

พนกงานขายคนท 2

{ รหสพนกงาน: 105

ชอพนกงาน: Ms. Lilly Choose

ยอดขาย: 950,000

Commission: 27,500.00

}

พนกงานขายคนท 3

{ รหสพนกงาน: 206

ชอพนกงาน: Mr. Jacky Wong

ยอดขาย: 1,000,000

Commission: 29,000.00

}

ตวอยางขอมลเรมตน

พนกงานรหส 100 พนกงานรหส 206 พนกงานรหส 105