C Revision

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

IT628 Systems Programming

C Programming Revision
Why C for Systems Programming ?
• Unix/Linux OS has been written in C/C++, hence call to system
functions is easier in C.
• C can perform memory management through dynamic memory
allocation.
• C can implement different data structures efficiently using structures
and pointers such as stack, queues, linked list, trees etc.
• Using C, hardware systems can be programmed directly.
• C can call assembly routines and assembly code can call C routines on
many processors if required.
C – Primitive Data types
• char : character - 1 byte • %d: integers
• short: short integer - 2 bytes • %f: floating point
• int: integer - 4 bytes • %c: characters
• long: long integer - 4 bytes • %s: string
• float: floating point - 4 bytes • %x: hexadecimal
• double - double precision • %u: unsigned int
floating point - 8 bytes
Operators
• Arithmetic: + - / * %
• Relational: > >= < <= == !=
• Logical: && || !
• Increment and Decrement: ++ and -- (pre and post)
• Bitwise: & | ^ << >> ~
• Assignment: = += -= /= *= %= &= |= ^= <<= >>=
• Ternary: ?:
• Special: .(dot) -> (structure member access using pointer)
Constants, Macros and Variables
#define COURSE “Systems int i;
Programming” float f = 10.8f;
#define NO_OF_STUDENTS 120 double d = 17.8;
#define max(a,b) a>b?a:b char c = 65;
C Statements
• Conditionals
• IF, IF-ELSE, Nested IF-ELSE
• switch..case…default
• Loops
• for(initialization;condition;iteration)
• while
• do..while
• break
• Continue
• goto
Arrays
• Arrays can be of primitive data type
int, float, double, char
• Array can be of user defined data type
using typedef
typedef char20 char[20];
char20 c20arr[10];
• Array can be of structure or union
struct user {
int user_id;
char[20] user_name;
};
struct user users[20];
What are the different ways to initialize the
array values ?
int a[10]={0,1,4,6,7,12,8,9,-1,34};
char c[3]={‘a’,’b’,’c’};
int b[3][2]={{2,5},{6,10},{-1,6}};
struct user u[2]={{1,”xyz”},{2,”abc”}}
OR
• Similarly using loops when don’t know the input values
for(i=0; i<10; i++)
scanf(“%d”, &a[i]);
for(i=0; i<3; i++) {
for(j=0;j<2;j++)
scanf(“%d”, &b[i]);
}
Strings
Difference between Character Array and String
• Character Array does not have a ‘\0’ (NULL) to
represent the end i.e. last character is regular
ASCII character
I n t r o 2 p r o g
• String ALWAYS has ‘\0’ as a last character to
represent end of string.
I n t r o 2 p r o g \0
Difference between Character Array and
String - How to read user input ?
All 10 locations will have Only first 9 locations can
ASCII Character value be used for storing actual
char c_arr[10]; string characters, last one
for (i=0; i<10; i++) will have ‘\0’
scanf(“%c”,&c_arr[i]) char str[10];
; OR scanf(“%s”, str); OR
c_arr[i] = getchar();
gets(str);
String Functions – Does not work for
Character Array
• strlen(s) – returns the length of the string excluding
‘\0’
• strcmp(s1, s2) – returns 1 (+ve No) if s1 > s2, -1 (-ve
No) if s1 < s2 and 0 if s1 equals s2
• strcpy(dst, src) – copies src string into dst string
• strcat(s1, s2) – returns concatenation of two string
(i.e. s1+s2)
• strstr(lrgstr, smlstr) – index of 1st occurrence of
smlstr into lrgstr
Memory Allocation for Variables
Declare variable int count and unsigned
char c (what is difference between signed
and unsigned value?)
Defining Pointers for primitive types
int i = 8, j=8; p1 == p2
int *p, *p1, *p2; *p1 == *p2
p = &i; p1=&i; p2=&j; p == p1
double *d = &i // will this work? What will be the result in each case?
double d1 = i // will this work?
double d2=1000.0008; int k = 8; int *p3;
i = d2; //will this work? p3 = &k; *p3 = 12;
i = (int) d2; will this work? What (int) in this Value of k?
case?
Note: * Has 2 uses: 1. for pointer declaration 2.
sizeof(p) == sizeof(d) for getting the data value pointed by pointer
variable
sizeof(*p) == sizeof(*d)
C_revision\pointers_knowledge_check.c
Arrays and Pointers
int a[10], *ptr; ptr[7] = 10; // will this work?
ptr= &a[0]; // ptr will point to first ptr=a; // will this work?
array element
printf(“%d”, *(ptr+5) );// ptr+ 5 = ? printf(“%d”, *ptr++);
printf(“%d”, *(ptr++));
If address of a[0] is 2000 then What is the difference?
what will be the value of ptr+ 5?

Be aware of precedence of
operators
Structures and Pointer to Structures
Structures and Pointer to Structures
Functions: Library and User Defined

Library User Defined


• From stdio.h: printf, scanf • Definition, Declaration and Call
• From string.h: strcpy, strcmp, strstr, • Scope of the variables
strlen, strcat • Pass parameters by value or by
• From unistd.h: read, write, lseek reference (difference
• From stdlib.h: open, close ?)C_revision\pass_by_value_or_ref.c
• Defined in same file vs different file
• Use of Header file: extern functions
C_revision\file1_main.c,
C_revision\file2_other.c,
C_revision\myheader.h
• Recursion
C pointer to array function
• Declare Array of Function pointers and initialize
int add(int a, int b);
int sub(int a, int b);
int mul(int a, int b);
int div(int a, int b);
int (*oper[4])(int a, int b) = {add, sub, mul, div};
• Call the function using initialized function pointer array
int result = oper[i](a,b);
C_revision\function_ptr_example.c
Recursive Functions – Calls itself until
terminating condition
int fibo(int num) {
if (num == 0) {
return 0;
}
else if (num == 1) {
return 1;
}
else {
return(fibo(num - 1) + fibo(num - 2));
}
}
Dynamic Memory Management
#include <stdlib.h>
int a[10];
int *ptr_i = (int *) malloc(10 * sizeof(int));
Are these equivalent?
You must call free() for any pointer which has been allocated a memory. What
problem will it cause if you don’t?

Similarly you can use pointer to structure to access the members of the structure
struct person { int p_id; char p_name[20];} *p
p = (struct person *) malloc(sizeof(person)); // will store only 1 person info
scanf(“%d”,&p->p_id); scanf(“%s”, p->p_name);
Data structures using C pointers
• Array vs Linked List
Data structures using C pointers
• Singly vs Doubly Linked List
Data structures using C pointers
• Singly Regular vs Singly Circular Linked List
Data structures using C pointers
• Singly Circular vs Doubly Circular Linked List
Other Data structure implementation - Stack
Other Data structure implementation - Queue
Other Data structure implementation - Trees
• Binary Trees: Binary Tree, Binary Search Tree, AVL Tree, Red-Black
Tree, Splay Tree
• B-Tree: B-Tree, B+ Tree, B sharp tree
• General Trees: Trie, Radix Tree, Suffix Tree, B Trie
• Multiway Tree: Ternary Tree, K-ary Tree, And-or Tree, (a,b)-tree
• Space Partitioning Tree: K-d Tree, R-tree, Segment tree, Range tree,
Octree, Herbert R-tree
• Application Specific Tree: Parse Tree, Decision Tree, MinMax Tree,
Expression Tree
Example for Circular Double Linked List
struct user {
int user_id;
char[20] user_name;
struct user *prev;
struct user *next;
} head, tail;
Example for Circular Doubly Linked List
Adding a new node in the list:
struct user *new = (struct user *)malloc(sizeof(struct));
new->user_id=<new id>; new->user_name=<new name>;
new.next = NULL; new.prev = NULL;
if(head == NULL)
head = new; tail = new; head->prev = head; head->next = head
else {
tail->next = new;
new->prev = tail;
new->next = head;
head->prev = new;
tail = new;
}
Example for Circular Doubly Linked List
Delete a new node from the list for a given user_id
if(head==NULL) {
struct user temp;
for(temp=head; temp!=NULL; temp->next)
if(temp->user_id == <given user_id>)
break;
if(temp != NULL) {
temp->prev->next = temp->next;
temp->next->prev = temp->prev;
temp->prev=NULL;
temp->next=NULL;
free(temp);
}
}
Headers defined by the ISO (International
Standard Organization) C standard
• <assert.h> : Conditionally compiled macro that compares its argument to zero
• <complex.h> (since C99) : Complex number arithmetic
• <ctype.h> : Functions to determine the type contained in character data
• <errno.h> : Macros reporting error conditions
• <fenv.h> (since C99) : Floating-point environment
• <float.h> : Limits of float types
• <inttypes.h> (since C99) : Format conversion of integer types
• <iso646.h> (since C95) _ Alternative operator spellings
• <limits.h> : Sizes of basic types
• <locale.h> : Localization utilities
• <math.h> : Common mathematics functions
• <setjmp.h> : Nonlocal jumps
• <signal.h> : Signal handling
• <stdalign.h> (since C11) : alignas and alignof convenience macros
• <stdarg.h> : Variable arguments
Headers defined by the ISO (International
Standard Organization) C standard
• <stdatomic.h> (since C11) : Atomic types
• <stdbool.h> (since C99) : Boolean type
• <stddef.h> : Common macro definitions
• <stdint.h> (since C99) : Fixed-width integer types
• <stdio.h> : Input/output
• <stdlib.h> : General utilities: memory management, program utilities, string conversions, random numbers
• <stdnoreturn.h> (since C11) : noreturn convenience macros
• <string.h> : String handling
• <tgmath.h> (since C99) : Type-generic math (macros wrapping math.h and complex.h)
• <threads.h> (since C11) : Thread library
• <time.h> : Time/date utilities
• <uchar.h> (since C11) : UTF-16 and UTF-32 character utilities
• <wchar.h> (since C95) : Extended multibyte and wide character utilities
• <wctype.h> (since C95) : Functions to determine the type contained in wide character data
Required Headers for IEEE POSIX (Portable
Operating System Interface) Standard (This is in
addition to ISO C Standard)
• <direct.h> : directory entries
• <fcntl.h> : file control
• <fnmatch.h> : filename-matching types
• <glob.h> : pathname-pattern matching types
• <grp.h> : group file
• <netdb.h> : network database operation
• <pwd.h> : password file
• <regex.h> : regular expressions
• <tar.h> : tar archive values
• <termios.h> : terminal I/O
• <unistd.h> : symbolic constants
• <utime.h> : file times
• <wordexp.h> : word-expansion types
Required Headers for IEEE POSIX (Portable
Operating System Interface) Standard (This is in
addition to ISO C Standard)
• <arpa/inet.h> : Internet definition
• <net/if.h> : socket local interface
• <netinet/in.h> : internet address family
• <netinet/tcp.h> : Transmission Control Protocol definition
• <sys/nman.h> : memory management declaration
• <sys/select.h> : select function
• <sys/socket.h> : socket interface
• <sys/stat.h> : file status
• <sys/times.h> : process times
• <sys/types.h> primitive system datatypes
• <sys/un.h> : UNIX domain socket definition
• <sys/utsname.h> : system name
• <sys/wait.h> process control
Exercise Setup
• You are given a task to keep track of number of queries running in
database management system. Below information regarding queries
need to be kept in C structure.
struct query {
int query_id; // unique id
char* query_text; // actual query text
int status; // submitted, running, finished
int time_elapsed; // time in microsec it took to run the query
}
Exercise Problem 1
• Create an array of structure for struct query defined previously using
dynamic memory allocation and to provide the following functions.
For each of functionality you can use user menu selection
• New query is submitted by a SQL developer i.e. new array entry is added with
status as submitted
• Query has started running so update to running
• Query is running so periodically need to update time_elapsed
• Query has finished running so update the status as finished and remove the
entry from array
Exercise Problem 2
• Functionality of Problem 2 is same as Problem1
• New query is submitted by a SQL developer i.e. new array entry is added with
status as submitted
• Query has started running so update to running
• Query is running so periodically need to update time_elapsed
• Query has finished running so update the status as finished and remove the
entry from array
• But Problem 2 should be implemented using linked list instead of
array

• Complete the code in C_revision\excercise2.c

You might also like