Copyright 2000-2018 Networking Laboratory
C programming and
Data Structures Overview
T. H. Cormen, C. E. Leiserson and R. L. Rivest
Introduction to Algorithms, 3rd Edition, MIT Press, 2009
Sungkyunkwan University
Hyunseung Choo
Algorithms
Contents
Functions
Invocations Function
Function Definitions Return
statements
Function Prototypes
Call by value and call by
reference
Recursions
Recursive Call
Examples
Structures
Struct Declaration
Structure Tag
Compatible Structure
Memory Allocation
Accessing a Member
Pointers
Pointer Variable
Passing Pointers to Functions
Exercise Problem
Networking Laboratory 2/78
Algorithms
Functions
Networking Laboratory 3/78
Algorithms
Invocations Function (1/3)
Function
C 프로그램은하나이상의 Function들로구성
모든 c-program은반드시한개의 main() Function을포함
반복되는 codes의경우 function으로정의하여필요시마다그
function을호출하여사용함으로서 simplicity의향상
Function의종류
Library functions : System이제공하는 Predefined-Functions
User-defined functions : Programmer에의해작성된 Functions
Function Invocation
Function의호출 : Function_name() 의형식으로사용.
Function의종료 : Function을 Call한곳으로제어권의이동
Networking Laboratory 4/78
Algorithms
Invocations Function (2/3)
Networking Laboratory 5/78
Algorithms
Invocations Function (3/3)
Networking Laboratory 6/78
Algorithms
Function Definitions (1/2)
Function이호출되기전반드시해당 Function을다음형식
으로정의해야한다.
Networking Laboratory 7/78
Algorithms
Function Definitions (2/2)
Parameter Type List
Function 호출시전달되는 arguments에대응되는순서와 data
types을지정
Function body내에서 identifier로사용될수있다
Return type
Function 종료될때 return statement에의해전달되는 value 의 type.
Default type : integer type으로, 생략시자동 integer로간주
void type : Return Value가없는경우 void로지정
Networking Laboratory 8/78
Algorithms
The Return Statement
Function의실행종료, 호출한곳으로 control을이전하는
statement
생략시는 function body 끝의 ‘}’를만났을때자동 return
복수개의 return문사용가능
단, 하나의 Function에서두개의값을동시에 return할수없음
Networking Laboratory 9/78
Algorithms
The Return Value
Networking Laboratory 10/78
Algorithms
Function Prototypes (1/2)
Function 사용을위해호출전에반드시필요한 Function 선
언문
prototype이생략가능한경우
모든조건이 default인경우생략가능 : return value의 type과
argument의 type이 integer인경우생략가능
function이 main() function전에정의된경우
선언형식
return-type function_name (parameter type list);
Networking Laboratory 11/78
Algorithms
Function Prototypes (2/2)
Argument와 parameter의 type이일치하지않는경우
function prototype에서지정된 type으로 convert됨.
Networking Laboratory 12/78
Algorithms
Function Definition Order
한개의 file로작성된 program의일반적순서
1. #include, #define statements
2. Enumeration types and typedef
3. struct definition
4. Function Prototypes
5. main() Function
6 Function Definitions
Networking Laboratory 13/78
Algorithms
main( )안에서의 Function Definition
Networking Laboratory 14/78
Algorithms
Developing Large Program (1/2)
대규모 Program의경우, 여러 ~.h 파일과 ~.c파일로나누어
작성할수있다.
Team에의한작업분담이용이해진다.
프로그램이변경될때마다변경된 ~.c 파일만을 compile함
으로서시간절약가능
Networking Laboratory 15/78
Algorithms
Developing Large Program (2/2)
Networking Laboratory 16/78
Algorithms
Call by Value and Call by Reference
Call-by-Value
Function Invocation이일어나면, argument의 value를전달받기위
한 parameter를위해메모리영역이새로생기며 argument의값이
새영역에 copy된다.
Function Invocation의 parameter를 identifier로사용하여그값을
function내에서변경한경우에도다른 memory영역을사용함으로써
실제 argument의값은변경되지않는다
Call-by-Reference
Function Invocation이일어나면 argument의 address를전달한다.
실제값의 address를변경하기때문에그값을 function내에서변경
한경우실제 argument값이변경된다.
Networking Laboratory 17/78
Algorithms
Example of Call by Value
Networking Laboratory 18/78
Algorithms
Example of Call by Reference
Networking Laboratory 19/78
Algorithms
Recursions
Networking Laboratory 20/78
Algorithms
Recursive Call
어떤함수가자기자신을호출하는것
Networking Laboratory 21/78
Algorithms
Factorial을구하는예제
Networking Laboratory 22/78
Algorithms
Array의평균을구하는예제
Networking Laboratory 23/78
Algorithms
Drawing Patterns on the Screen (1/2)
제곱근을구하는예제
Networking Laboratory 24/78
Algorithms
Drawing Patterns on the Screen (2/2)
역순으로문자를출력하는예제
입력받은문장의문자들을역순으로출력한다.
Networking Laboratory 25/78
Algorithms
Structures
Networking Laboratory 26/78
Algorithms
Array와 structure의차이점
array
Array의모든 element는같은 type이여야한다.
Index를사용하여각 element를 access한다.
structure
다른 type의 element로구성될수있다있다.
각 element는 name을갖는다.
Name에의해각 element를 access한다.
Networking Laboratory 27/78
Algorithms
Struct Declaration
Collection of members(/elements)
Networking Laboratory 28/78
Algorithms
Structure Tag
정의되는특정 structure를지정하기위한 name
한번 structure tag인 part가정의되면, 이제 tag를사용하여
같은 structure type으로선언할수있다.
Networking Laboratory 29/78
Algorithms
Structure Tag와변수동시선언
structure tag를이용하여선언된변수는같은 structure type
Networking Laboratory 30/78
Algorithms
Compatible Structure (1/2)
같은 type의 structure variable이면서로 assign 가능
compatible types의조건
Structure 정의와동시에선언되는모든 variables
같은 type의 structure 즉같은 tag에의해선언된모든 variables
Networking Laboratory 31/78
Algorithms
Compatible Structure (2/2)
compatible type이아닐경우 =, ==, != 불가능
Networking Laboratory 32/78
Algorithms
Memory Allocation
Structure로선언된데이터 type은
각 member들이메모리내에
순차적으로할당된다.
part1의 base address가 200이고,
integer size가 4byte라가정하면,
오른쪽그림과같이메모리가할당됨
Networking Laboratory 33/78
Algorithms
Accessing a Member (1/3)
struct member operator ‘.’
Structure의각 member를 access하기위해 ‘.’를사용한다.
Networking Laboratory 34/78
Algorithms
Accessing a Member (2/3)
member operation
Networking Laboratory 35/78
Algorithms
Accessing a Member (3/3)
structure pointer
Networking Laboratory 36/78
Algorithms
Structures as Argument
call-by-value로 struct가 copy되어사용된다.
Networking Laboratory 37/78
Algorithms
Struct Pointer사용 (1/2)
call-by-reference로 struct의 address를전달한다.
Networking Laboratory 38/78
Algorithms
Struct Pointer사용 (2/2)
Networking Laboratory 39/78
Algorithms
The Use of typedef (1/2)
data type의 name을재정의하기위해사용
readability의증가
Networking Laboratory 40/78
Algorithms
The Use of typedef (2/2)
typedef를사용, struct type을새로운 type으로선언
Networking Laboratory 41/78
Algorithms
Pointers
Networking Laboratory 42/78
Algorithms
Pointer Variable
포인터변수는변수명은같으나변수선언을할때 * 연산자
를사용한다.
int *a; → int형포인터
포인터변수는타입에상관없이 4바이트다.
Networking Laboratory 43/78
Algorithms
Passing Pointers to Functions (1/4)
포인터를 argument로하는함수예제
Networking Laboratory 44/78
Algorithms
Passing Pointers to Functions (2/4)
포인터를 argument로하는함수예제
Networking Laboratory 45/78
Algorithms
Passing Pointers to Functions (3/4)
포인터를 argument로하는함수예제
Networking Laboratory 46/78
Algorithms
Passing Pointers to Functions (4/4)
포인터를 argument로하는함수사용시유의점
Networking Laboratory 47/78
Algorithms
Exercise Problem
pointer의주소할당문제
Networking Laboratory 48/78
Algorithms
Approaches
pointer의예제
Networking Laboratory 49/78
Copyright 2000-2018 Networking Laboratory
Data Structures Overview
Sungkyunkwan University
Hyunseung Choo
Algorithms
Contents
Arrays
Arrays
Representation of
Multidimensional Arrays
Stacks and Queues
Stack Abstract Data Type
Queue Abstract Data Type
Circular Queues
Lists
Singly Linked Lists
Doubly Linked Lists
Networking Laboratory 51/78
Algorithms
Arrays
Networking Laboratory 52/78
Algorithms
Arrays (1/2)
An array is a set of pairs, <index, value>, such that each
index that is defined has a value associated with it
A consecutive set of memory locations in C
Logical order is the same as physical order
int list[5], *plist[5];
/* arrays start at index 0 in C */
- integers: list[0],..., list[4]
- int ptrs: plist[0],..., plist[4]
Networking Laboratory 53/78
Algorithms
Arrays (2/2)
Variable Memory Address
list[0] base address = a
list[1] a + sizeof(int)
list[2] a + 2·sizeof(int)
list[3] a + 3·sizeof(int)
list[4] a + 4·sizeof(int)
list[i] in C programs, C interprets it as a pointer to an integer whose
address is the one in the table above
int *list1;
pointer variable to an int
int list2[5];
five memory locations for holding integers are reserved
Networking Laboratory 54/78
Algorithms
Representation of Multidimensional Arrays
Internal Representation of Multidimensional Arrays
How to state n-dimensional array into 1-dimensional array?
How to retrieve arbitrary element in a[upper0][upper1]···[uppern-1]
the number of elements in the array
n-1
P upperii=0
e.g.) a[10][10][10]
→ 10*10*10 = 1000 (units)
Networking Laboratory 55/78
Algorithms
1-dimensional Array
Starting-address + offset-value
Assume a: starting-address
1-dimensional array a[u0]
a[0] : a
a[1] : a + 1
: :
a[u0-1] : a + (u0 - 1)
&a[i] = α + i
Networking Laboratory 56/78
Algorithms
2-dimensional Array
2-dimensional array a[u0][u1]
a[i][j] = α + i·u1 + j
0 1 · · · u 1 - 1
0 a a + 1 a +(u 1-1)
1
·
·
·
u 0 - 1
?i
j
Networking Laboratory 57/78
Algorithms
Stacks and Queues
Networking Laboratory 58/78
Algorithms
Stack Abstract Data Type
ADT stack Last-In-First-Out (LIFO) Ordered list, insertions and deletions are made at one end called
the “top”
Given stack S = (a0, ···, an-1)
a0 : bottom element
an-1 : top element
ai : on top of element ai-1 (0<i<n)
Inserting and deleting elements in stack
topA
topB
A
topC
B
A
topD
C
B
A
topE
D
C
B
A
topD
C
B
A
Networking Laboratory 59/78
Algorithms
Implementing a Stack
Using a one-dimensional array stack[MAX_STACK_SIZE]
#define MAX_STACK_SIZE 100
typedef struct {
int key;
} element;
element stack[MAX_STACK_SIZE];
int top = -1;
Structure element consists of only a key field, and we can add
fields to or modify to meet the requirements of the application
Networking Laboratory 60/78
Algorithms
Push and Pop
Pushvoid push(int *ptop, element item) {
if (*ptop >= MAX_STACK_SIZE - 1) {
stack_full();
return;
}
stack[++*ptop] = item;
}
Pop
element pop(int *ptop) {
if (*ptop == -1)
return stack_empty();
return stack[(*ptop)--];
}
push(&top, item)
pop(&top, item)
Networking Laboratory 61/78
Algorithms
ADT queue First-In-First-Out (FIFO)
Ordered list
All insertions are made at one end called “rear”
All deletions are made at the other end called “front”
Inserting and deleting elements in queue
Queue Abstract Data Type
rearA
rearB
A
rearC
B
A
rearD
C
B
A
rearD
C
B
front
frontfrontfrontfrontfront
& rear
A
Networking Laboratory 62/78
Algorithms
Implementing a Queue
A one-dimensional array, and two variables: front and rear
#define MAX_QUEUE_SIZE 100
typedef struct {
int key;
/* other fields */
} element;
element queue[MAX_QUEUE_SIZE];
int rear = -1;
int front = -1;
Networking Laboratory 63/78
Algorithms
Add and Delete
Add to a queue
void addq(int *prear, element item) {
if (*prear == MAX_QUEUE_SIZE - 1) {
queue_full();
return;
}
queue[++*prear] = item;
}
Delete from a queue
element deleteq(int *pfront, int rear) {
if (*pfront == rear)
return queue_empty();
return queue[++*front];
}
In deleteq()
rear is used
to check for
an empty
queue
addq(&rear, item)
deleteq(&front, rear)
Networking Laboratory 64/78
Algorithms
Circular Queues (1/3)
More efficient queue representation
Regarding the array queue[MAX_QUEUE_SIZE] as circular
Initially front and rear to 0 rather than -1
The front index always points one position counterclockwise from
the first element in the queue
The rear index points to the current end of the queue
Networking Laboratory 65/78
Algorithms
Circular Queues (2/3)
Empty queue
[1]
[2] [3]
[4]
[0] [5]
front = 0
rear = 0
[1]
[2] [3]
[4]
[0] [5]
front = 0
rear = 3
J3
J1
J2
Empty and nonempty circular queues
Networking Laboratory 66/78
Algorithms
Circular Queues (3/3)
Full queue
[1]
[2] [3]
[4]
[0] [5]
front = 0
rear = 5
[1]
[2] [3]
[4]
[0] [5]
front = 4
rear = 3
J9
J7
J8
J1
J2 J3
J4
J5 J6 J5
Full circular queues
Networking Laboratory 67/78
Algorithms
Implementing Insertions and Deletions
Use modulus operator
Circular rotation of the rear
*rear = (*rear + 1) % MAX_QUEUE_SIZE
Circular rotation of the front
*front = (*front + 1) % MAX_QUEUE_SIZE;
Networking Laboratory 68/78
Algorithms
Add to a Circular Queue
Add an item
void addq(int front, int *rear, element item)
{
*rear = (*rear + 1) % MAX_QUEUE_SIZE;
if (front == *rear) {
queue_full(rear);
/* reset rear and print error */
return;
}
queue[*rear] = item;
}
rotate rear before we place the item in queue[rear]
addq(front, &rear, item)
Networking Laboratory 69/78
Algorithms
Delete from a Circular Queue
Delete an item
element deleteq(int *front, int rear)
{
element item;
if (*front == rear)
return queue_empty();
/* queue_empty returns an error key */
*front = (*front + 1) % MAX_QUEUE_SIZE;
return queue[*front];
}
deleteq(&front, rear)
Networking Laboratory 70/78
Algorithms
Lists
Networking Laboratory 71/78
Algorithms
Singly Linked Lists
Compose of data part and link part
Link part contains address of the next element in a list
Non-sequential representations
Size of the list is not predefined
Dynamic storage allocation and deallocation
bat satcat vat NULL
ptr
Networking Laboratory 72/78
Algorithms
Insertion of Singly Linked Lists
To insert the word mat between cat and sat
1) Get a currently unused node (paddr)
2) Set paddr’s data to mat
3) Set paddr’s link to point to the address found in the link of the node
cat
4) Set the link of the node cat to point to paddr
bat satcat vat NULL
ptr
mat
Networking Laboratory 73/78
Algorithms
Deletion of Singly Linked Lists
To delete mat from the lists
1) Find the element that immediately precedes mat, which is cat
2) Set its link to point to mat’s link
- No data movement in insert and delete operation
bat satcat vat NULL
ptr
mat
Networking Laboratory 74/78
Algorithms
Doubly Linked Lists (1/2)
Problems of singly linked lists
Move to only one way direction
Hard to find the previous node
Hard to delete the arbitrary node
Doubly linked circular lists
Doubly lists + circular lists
Allow two links
Two way direction
Networking Laboratory 75/78
Algorithms
Doubly Linked Lists (2/2)
Doubly linked circular lists with head node
head node
llink item rlink
Networking Laboratory 76/78
Algorithms
Insertion of Doubly Linked Lists
Insertion into doubly linked circular listsvoid dinsert(node_ptr node,node_ptr newnode) {
/* insert newnode to the right of node */
newnode->llink = node;
newnode->rlink = node->rlink;
node->rlink->llink = newnode;
node->rlink = newnode;
}
time: O(1)
1.
2.
3.
4.
dinsert(node, newnode)
newnode
node
341 2
node
newnode
1
23
4
newnode
node
Networking Laboratory 77/78
Algorithms
Deletion of Doubly Linked Lists
Deletion from a doubly linked circular listsvoid ddelete(node_ptr node, node_ptr deleted) {
/* delete from the doubly linked list */
if (node == deleted)
printf(“Deletion of head node not permitted.\n”);
else {
deleted->llink->rlink = deleted->rlink;
deleted->rlink->llink = deleted->llink;
free(deleted);
} }
time: O(1)
node
deleted
node
ddelete(node, deleted)
deleted
node
Networking Laboratory 78/78