Lec01 ReviewCProgramming
Lec01 ReviewCProgramming
1
Lecturer Information
Dr. Tong Van Van
School of Information and Communication Technology,
Hanoi University of Science and Technology
• Office : 405-B1
• E-mail : [email protected]
• Google Scholar:
https://scholar.google.com/citations?user=XKJm_fQAAAA
J&hl=en
2
Course information
• IT4062: Network programming
• What we study in this course
▪ How to build network applications using socket programming
paradigm.
▪ Socket programming using C (in details)
3
Course information
• References
▪ Documents of professional group related to subject: Network
Programming.
▪ Unix Network Programming Vol.1, 3rd edition, W.Richard Stevens,
Prentice-Hall
▪ Internetworking with TCP/IP vol.3, Client-Server Programming
and Applications (BSD version), Douglas E. Comer, David L.
Stevens, Prentice-Hall
▪ TCP/IP Sockets in C: Practical Guide for Programmers, Michael
Donahoo, Kenneth Calvert, Elsevier Science
4
Course information
• Exercises in class
▪ After each lecture
▪ Used for mid-term evaluation
• Final project
▪ Development of network applications in groups
▪ 2-3 members/ group
▪ Used for final evaluation
• Grading
▪ Exercises (50%)
▪ Final project (50%)
5
Course information
• Email for submitting exercises: [email protected]
• Subject: Homework X
7
REVIEW C PROGRAMING
Tong Van Van, SoICT, HUST
8
Content
• Data type
• Condition and Iteration
• Function
• Command line argument
• Pointer
• Structure
• Link listed
• I/O function
9
Data type
• Integer
• int, char, short, long
• Floating
• double, float
• Array
• Collection of A data type
• Declare : int a[10];
10
Size of Type
11
Condition and Loop Structure
• if … else
• switch
• for
• while, do … while
12
Condition
• a == b
• b equals to a
• a != b
• b is different to a
• a>b
• b is smaller than a
• a >= b
• b isn’t greater than a
• a<b
• b is greater than a
• a <= b
• b isn’t smaller than a
13
if … else
if(condition){ if (condition)
statement1; task1;
… else task2;
}
else{
statement2; is equivalent?
…
}
if (condition)
task1;
Example :
if (!condition)
if( x == 1){
task2;
y = 3;
z = 2;
}
else{
y = 5;
z = 4;
}
14
switch
switch(condition){
case value1: statement1;…; break;
case value2: statement2;…; break;
…
default: statement;…; break;
}
Example :
int monthday( int month ){
switch(month){
case 1: return 31;
case 2: return 28;
…
case 12: return 31;
}
}
15
for
• expr1, expr3: assignments or function calls
• expr2: relational expression
Any of the three expression can be omitted
• the semicolons must remain
for(expr1;expr2;expr3){
statements;
…
}
Example:
for( x = 0; x < 10; x++){
printf(“%d\n”, x);
}
16
while, do…while
• If there is no initialization or re-initialization, the while is
most natural
while ((c = getchar()) == ' ' || c == '\n' || c = '\t')
/* skip white space characters *
while(condition){ do{
statement; statement;
… …
} } while(condition)
Example: Example:
x = 0; x = 0;
while(x < 10){ do{
printf(“%d\n”,x); printf(“%d\n”,x);
x = x + 1; x = x + 1;
} } while(x < 10)
17
break
• break
• Terminates the execution of the nearest enclosing loop or conditional
statement in which it appears.
• continue
• Pass to next iteration of nearest enclosing do, for, while statement in
which it appears
• Example
/* trim: remove trailing blanks, tabs, newlines */
char s[MAX]
int n;
for (n = strlen(s)-1; n >= 0; n--)
if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n')
break;
s[n+1] = '\0';
19
Example of function
#include <stdio.h>
int squaresub(int a)
{ Data type of function
return a*a;
} Return value statement
int main()
{
int b = 10;
printf("%d\n", squaresub(5));
return 0; Use function
}
20
Usage of command line arguments
• main( int argc, char **argv) Example :
• main( int argc, char *argv[]) %./a.out 123 456 789
arg[0]: ./a.out
• Argc : number of arguments arg[1]: 123
• argv[0] : argument 0 arg[2]: 456
• argv[1] : argument 1 arg[3]: 789
• argv[2] : argument 2
21
Pointer
Address
• Pointer variable
• "Variable" refers to
variable 108 i
• int i = 10;
104 j
• int j = 20;
100 ptr
• int *ptr;
• Pointer to pointer:
int **p;
0 Variables and addresses
22
Pointer (cont)
Address
• int i = 10;
• int j = 20;
• int *ptr = &i; 108 i 10
104 j 20
• printf(“i=%d\n”, &i)
100 ptr 108
• printf(“ptr=%d\n”, ptr)
• printf(“i=%d\n”, i)
• printf(“*ptr=%d\n”,*ptr)
• Ptr refers to the pointer variable 0
Variables and addresses
23
Pointer (cont)
• int x=1, y=5;
• int z[10];
• int *p;
• p=&x; /* p refers to x */
• y=*p; /*y is assigned the value of x*/
• *p = 0; /* x = 0 */
• p=&z[2]; /* p refer to z[2] */
24
Pointer and function
#include <stdio.h>
void swap(int x, int y) Result ?
{
int temp;
temp = x;
x = y;
y = temp;
}
int main(){
int a = 5;
int b = 3;
swap (a, b);
printf(“a=%d\n”, a);
printf(“b=%d\n”, b);
return 0;
}
25
Pointer and function (cont)
#include <stdio.h>
void swap(int x, int y) Address
{
int temp; 108 a
temp = x;
x = y; 104 b
y = temp;
}
26
Pointer and function (cont)
#include <stdio.h> Program to exchange 2 value of variables
void swap(int *x, int *y)
{
int temp; 108 a *x
temp = *x;
*x = *y; 104 b *y
*y = temp;
}
int main(){
int a = 5; 94 x 108
int b = 3;
90 y 104
swap (&a,&b);
printf(“a=%d\n”, a);
printf(“b=%d\n”,b);
return 0;
} 0
27
Pointer and Array
• The declaration an integer array a[0] a[1] … … … a[9]
int a[10];
• If pa is a pointer to an integer:
int *pa; pa pa+1 pa+2
pa = &a[0];
• Similarity: pa and a are pointers
• Difference: pa is a variable but a is not
• legal: pa ++; pa = a;
• Illegal: a++; a = pa;
• a: constant pointer
28
Constant pointer vs Pointer to constant
29
Constant pointer
#include <stdio.h>
int main(void)
{
int var1 = 0, var2 = 0;
int *const ptr = &var1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}
30
Pointer to constant
#include <stdio.h>
int main(void)
{
int var1 = 0;
const int* ptr = &var1;
*ptr = 1;
printf("%d\n", *ptr);
return 0;
}
31
Constant Pointer to a Constant
#include <stdio.h>
int main(void)
{
int var1 = 0,var2 = 0;
const int* const ptr = &var1;
*ptr = 1;
ptr = &var2;
printf("%d\n", *ptr);
return 0;
}
return 0;
}
33
void pointer
• void pointer: a special pointer that has no associated
data type with it
• Can hold address of any type and can be typcasted to any type.
• Generic programming
• Declaration: void *<name of pointer>;
• The void pointer cannot be dereferenced directly
• The void pointer must first be explicitly cast to another pointer type
before it is dereferenced.
#include <stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *(int *)ptr);
return 0;
}
34
Dynamic Memory Allocation
• A typical memory
representation of C program
consists of following
sections.
1. Text segment: code segment
2. Initialized data segment
3. Uninitialized data segment
4. Stack
5. Heap: the segment where
dynamic memory allocation
usually takes place
35
Dynamic Memory Allocation
• void * malloc( size_t size );
• Allocates requested size of bytes and returns a pointer to first byte
of allocated space
• Doesn’t initialize the allocated memory
• Asigment: ptr = (cast-type*) malloc(byte-size)
• void * calloc( size_t num, size_t size );
• Allocates space for an array elements, initializes to zero and then
returns a pointer to memory
• Initializes the allocates memory block to zero
• Asigment: ptr = (cast-type*)calloc(n, element-size);
• Equivalent:
ptr = malloc(size);
memset(ptr, 0, size);
36
Dynamic Memory Allocation
• void *realloc(void *ptr, size_t size);
• Deallocates the old object pointed to by ptr and returns a pointer to
a new object that has the size specified by size
• ptr = realloc(ptr, newsize);
• void free(void *ptr);
• Deallocate the previously allocated space
• Memory Leak
• Create a memory in heap and forget to delete it
• To avoid memory leaks, memory allocated on heap should always
be freed when no longer needed
• valgrind: suite of tools for debugging and profiling
programs.
$ valgrind –leak-check=full <program>
37
Structure
• Structure is a collection of variables under a single name.
Variables can be of any type: int, float, char etc.
• Declaring a Structure:
38
Using structure variable
• Declare structure variable?
int a;
• This is similar to variable declaration.
struct Customer John;
• Example
• Access structure members: use the dot operator
<structure variable name>.<member name>
• Access to members of a pointer to the variable structure:
using operators →
<structure variable name> -> <member name>
39
Example
struct student{
int id;
int score;
};
int main()
{
int i;
struct student students[5];
for(i=0; i<5; i++){
students[i].id = i;
students[i].score = i;
}
for(i=0;i<5;i++){
printf("student id:%d, score:%d\n",
students[i].id, students[i].score);
}
return 0;
}
40
Structure and Pointer
printf(“%d\n”, sp->score);
41
Link list
• Store a pointer to the next structure in the structure
struct student {
int id;
int score;
struct student *next;
}
• Warning : allocate memory before use and release
memory after use
*top
42
I/O function
Kernel
43
Input function (include in stdio.h)
• Functions
• printf( ) • getc( )
• Print formatted data to stdout • Character read from standard
• fprintf( ) input
• Write formatted output to stream • putc( )
44
Input function (include in unistd.h)
• Function
• read()
• Argument : number of bytes read and target
• write()
• Argument : the number of bytes to write to output
• open()
• close()
45
open()/read()/write()/close()
#include <fcntl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#define BUFSIZE 1024
int main()
{
char buf[BUFSIZE];
int fd;
int nbyte;
fd = open(“test.txt”, O_RDONLY, 0);
while((nbyte = read(fd, buf, BUFSIZE)) > 0) {
write(1, buf, nbyte);
}
close(fd);
return 0;
}
46
File handling functions
• fopen(char *filename, char *mode)
• r,w,a,r+,w+,a+
• fgets(char *s,int length,FILE *fd)
• fgetc(FILE *fd)
• fclose(FILE *fd)
47
Example
#include <stdio.h>
return 0;
}
48