advance topics of c language

91
MEHWISH MEHMOOD Overview of C Lang

Upload: mehwish-mehmood

Post on 06-Apr-2017

26 views

Category:

Education


3 download

TRANSCRIPT

Page 1: Advance  topics of C language

M E H W I S H M E H M O O D

Overview of C Lang

Page 2: Advance  topics of C language

Topics• Pointers• Malloc• Alloc• Calloc• Free• Realloc• Functions• Strings• Structures• Sorting• File handling

Page 3: Advance  topics of C language

Pointer

• ‘Pointer’ is a variable that contains a memory address of other variable (does not contain a actual data).This is why we call it “Pointer” since it is used to POINT other variable.

What Is pointer?

Page 4: Advance  topics of C language

Why we use pointer?

Some situations where pointers can be used are

To return more than one value from a function To pass arrays and strings more conveniently from one

function to another

To manipulate arrays easily by moving pointers to theminstead of moving the arrays itself

To allocate memory and access it (Direct Memory Allocation)

Page 5: Advance  topics of C language

5

Pointer

int main (){

int a;int b;int c;

…int* ptr;

a = 1000;b = 2000;c = 3000;

}

1000 2000 3000

int a int b int c

NUL

3004 3006

int* ptr

1004 1006 1008 1012

Page 6: Advance  topics of C language

6

Pointer

int main (){

int a;int b;int c;int* ptr;

a = 1000;b = 2000;c = 3000;ptr = &a;

}

1000 2000 3000

1004 1006 1008 1012

int a int b int c

1004

3004 3008

int* ptrmemory address of ‘a’

Page 7: Advance  topics of C language

7

int * p;

int* p;

int *p;

Pointer Declaration• Thus, the character * can appear anywhere

between the data type name and the variable name.• Syntax:

data_type *var_name;

Page 8: Advance  topics of C language

C provides two

operators to work with pointers.

(&) the address of operator

(*) the dereferencing

Pointers operators

is a unary operator that returns the address of its operand.For example, given the statements:

int x;int *p;

The statement: p = &x;

assigns the address of x to p. That is, x and the value of p refer to the same memory location

referred to as indirection operatorrefers to the object to which its operand (that is, the pointer) points.For example, given the statements:

int x=25,*p;p=&x

25

Xp

Page 9: Advance  topics of C language

9

Dereferencing Operator (*)• Consider the following statements.

1. num = 78;

2. p = #

3. *p = 24;

Page 10: Advance  topics of C language

Operations on pointer variables

Assignment • The value of one pointer variable can be assigned to

another pointer variable of the same type.

• Example:

• Note: Any changes made to *p automatically change the value of *q, and vice versa.

int *p,*q, i=5;q=&i; p=q;

Page 11: Advance  topics of C language

Operations on pointer variables

comparison• Two pointer variables of the same type can be

compared for equality, and so on.

• Example : int *p,*q, i=5;q=&i; p==q;p!=q;

evaluates to true if p and q have the same value that is, if they point to the same memory location. evaluates to true if p

and q point to different memory locations.

Page 12: Advance  topics of C language

Decrement and increment• Integer values can be added and subtracted from

a pointer variable.

• ++ increments the value of a pointer variable by the size of the memory to which it is pointing.

• Similarly, -- the value of a pointer variable by the size of the memory to which it is pointing.

Operations on pointer variables

Page 13: Advance  topics of C language

• Example :

• Let us assume that var is stored at the address 1000

• Then ptr_var has the value 1000 stored in it. Since integers are 2 bytes long, after the expression “ptr_var++;” ptr_var will have the value as 1002 and not 1001

int var,*ptr_var;

ptr_var=&var; var=500;Ptr_var++;

Operations on pointer variables

Page 14: Advance  topics of C language

Pointer to array

a &a[0]‘a’ is a pointer only to the first element, not the whole array

same

Page 15: Advance  topics of C language

Dereferencing array pointers

Page 16: Advance  topics of C language

Example #include<stdio.h>void main(){static int ary[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9,10};int i;for (i = 0; i < 10; i ++){

printf(“\ni=%d,ary[i]=%d,*(ary+i)=%d“,i, ary[i],*(ary + i)); printf(“&ary[i]= %X,ary+i=%X”,&ary[i],ary+i); /* %X gives unsigned hexadecimal */

}}

Page 17: Advance  topics of C language

Output

Page 18: Advance  topics of C language

Pointer to string

Page 19: Advance  topics of C language

Malloc()

•    The malloc()  function dynamically allocates memory when required. This function allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error.

Page 20: Advance  topics of C language

Example

Page 21: Advance  topics of C language

Calloc()•   calloc is similar to malloc, but the main

difference is that the

• values stored in the allocated memory space is zero by default

calloc requires two arguments The first is the number of variables you'd like to

allocate memory for The second is the size of each variable

Page 22: Advance  topics of C language

Example

Page 23: Advance  topics of C language

Realloc()• You've allocated a certain number of bytes for an

array but later find that you want to add values to it.You could copy everything into a larger array, which is inefficient, or you can allocate more bytes using realloc, without losing your data.

realloc takes two arguments The first is the pointer referencing the memory The second is the total number of bytes you want to

reallocate

Page 24: Advance  topics of C language

Reallaoc()

Syntax:

void *realloc( void *ptr, size_t size );

Page 25: Advance  topics of C language

Example

Page 26: Advance  topics of C language

Example

Page 27: Advance  topics of C language

Free()• free() function can be used to de-allocates (frees)

memory• when it is no longer needed.Syntax:void free(void *ptr );

• This function de allocates the space pointed to by ptr, • freeing it up for future use.

• ptr must have been used in a previous call to malloc(),• calloc(), or realloc().

Page 28: Advance  topics of C language

Example

Page 29: Advance  topics of C language

Functions

A function in C can have a value, a side effect, or both • The side effect occurs before the value is returned.

• The function’s value is the value of the expression in the return statement.

• A function can be called for its value, its side effect, or both.

Page 30: Advance  topics of C language

Function

Page 31: Advance  topics of C language

Function structure• The general syntax of a function in C is :

• The type_specifier specifies the data type of the value, which the function will return.

• A valid function name is to be assigned to identify the function

• Arguments appearing in parentheses are also termed as formal parameters.

Page 32: Advance  topics of C language

User-Defined Functions- Declaring, Calling, and

Defining

//Prototype declarationvoid greeting();int main(){greeting();return 0;} // main

Void greeting(){printf(“HELLO WORLD”);return ;} //greeting()

Declaration is coded

first

Definition is after the call

Call is in the

statement sections

Page 33: Advance  topics of C language

Functions without Return Value

(Only Have Side Effect)

Page 34: Advance  topics of C language

Function with return value

The type of the expression in the return statement must match the return type in the

function header.

. Only one value can be returned by a function

Page 35: Advance  topics of C language

Argument of a function• Formal parameters are variables that are declared in the

header of the function definition.

• Actual parameters are the expressions in the calling statement.

• The formal and actual parameters must match exactly in type, order, and number. Their names, however, do not need to be the same.

Page 36: Advance  topics of C language

Argument of a functionint square(int x);Int main(){Int IFor(i=1;i<10; i++){printf(“\n square of %d is %d:”, i, square(i));}

int square(int x){int j;j=x*x;return(j);}

Actual argument

Formal argument

Page 37: Advance  topics of C language

variables• Local Variables• Declared inside a function • Created upon entry into a block and destroyed upon exit

from the block • Formal Parameters• Declared in the definition of function as parameters • Act like any local variable inside a function

• Global Variables• Declared outside all functions • Holds value throughout the execution of the program

Page 38: Advance  topics of C language

Example float pi=3.1415;void area( int rad);int main(){float radius;    printf("\nEnter the radius of Circle : ");   scanf("%d", &radius);area(radius);Return 0;}Void area( int rad){int area;

area=pi*rad*rad;}

Global variable

Formal parameter

Local variable

Page 39: Advance  topics of C language

Storage Classes

Every C variable has a characteristic called as a storage class

The storage class defines two characteristics of the variable:

• Lifetime – The lifetime of a variable is the length of time it retains a particular value

• Visibility – The visibility of a variable defines the parts of a program that will be able to recognize the variable

Page 40: Advance  topics of C language

Storage Classes

• automatic

• external

• static

• register

Page 41: Advance  topics of C language

Function Scope rules• Scope Rules - Rules that govern whether one

piece of code knows about or has access to another piece of code or data • The code within a function is private or local to

that function • Two functions have different scopes• One function cannot be defined within another

function

Page 42: Advance  topics of C language

Calling The Functions

Call by value

Call by reference

Page 43: Advance  topics of C language

Pass by value

When arguments are passed to the called function, the values are passed through temporary variables

Page 44: Advance  topics of C language

Pass by reference• In call by

reference, the function is allowed access to the actual memory location of the argument and therefore can change the value of the arguments of the calling routine

Page 45: Advance  topics of C language

Nesting Function Calls

main(){

.

.

palindrome();..

}

palindrome(){

.

.getstr();reverse();cmp();..

}

Page 46: Advance  topics of C language

Function pointer• A pointer variable can be passed as a parameter to a function

either by value or by reference.

• In the function pointerParameters, both p and q are pointers. The parameter p is a reference parameter; the parameter q is a value parameter.

• Furthermore, the function pointerParameters can change the value of *q, but not the value of q. However, the function pointerParameters can change the value of both p and *p.

Page 47: Advance  topics of C language

Function pointer

Page 48: Advance  topics of C language

String The string is any sequence of characters

surrounded by double quotes.

• Strings are arrays of characters terminated by the NULL (‘\0’) character.

• The ‘\0’ null character is automatically added in the internal representation of a string.

Page 49: Advance  topics of C language

Declaring string variables

A typical string variable declaration is:.

char str[10];

str is a character array variable that can hold a maximum of 10 characters including the null terminator.  

Page 50: Advance  topics of C language

String I/O operations String I/O operations are carried out using functions from the

standard I/O library called stdio.h

The gets() function is the simplest method of accepting a string through standard input

Input characters are accepted till the Enter key is pressed

The gets() function replaces the terminating ‘\n’ new line character with the ‘\0’ character

Syntax :gets(str);

Page 51: Advance  topics of C language

String I/O operations The puts() function is used to display a string on the standard output

device.

Syntax :puts(str);

The scanf() and printf() functions are used to accept and display mixed data types with a single statement.

The syntax to accept a string is as follows:scanf(“%s”, str);

The syntax to display a string is as follows:printf(“%s”, str);

Page 52: Advance  topics of C language

String Functions

Functions for handling strings are found in the standard header file string.h. Few of the operations performed by these functions are:

• Concatenating strings• Comparing strings• Locating a character in a string• Copying one string to another• Calculating the length of a string

Page 53: Advance  topics of C language

The strcat() function Joins two string values

into one.

Syntax:

strcat(str1, str2);

Concatenates the str2 at the end of str1

The function returns str1

Page 54: Advance  topics of C language

The strcmp() function

Compares two strings and returns an integer value based on the results of the comparison.

Syntax:strcmp(str1, str2);

The function returns a value:• Less than zero if str1<str2• Zero if str1 is same as str2• Greater than zero if str1>str2

Page 55: Advance  topics of C language

Example

Page 56: Advance  topics of C language

The strchr() function

Determines the occurrence of a character in a string.

Syntax:strchr(str, chr);

The function returns a value:

• Pointer to the first occurrence of the character (pointed by chr) in the string, str

• NULL if it is not present

Page 57: Advance  topics of C language

Example

Page 58: Advance  topics of C language

The strcpy() function Copies the value in one

string onto another

Syntax:strcpy(str1,

str2);

The value of str2 is copied onto str1

The function returns str1

Page 59: Advance  topics of C language

The strlen() function Determines the length

of a string

Syntax: strlen(str);

The function returns an integer value for the length of str

Page 60: Advance  topics of C language

Passing Arrays to Functions When an array is passed as an argument to a

function, only the address of the array is passed

The array name without the subscripts refers to the address of the array

void main(){

int array[10];

.

.

fn_ary(array);..

}

Page 61: Advance  topics of C language

Example

#include<stdio.h> void main(){int num[5], ctr, sum=0;int sum_arr(int num_arr[]); /* Function declaration */ 

clrscr(); 

for(ctr=0;ctr<5;ctr++) /* Accepts numbers into the array */{

printf("\nEnter number %d: ", ctr+1);scanf("%d", &num[ctr]);

}

Page 62: Advance  topics of C language

Example sum=sum_arr(num); /* Invokes the function */

 printf("\nThe sum of the array is %d", sum);

 getch();

} int sum_arr(int num_arr[]) /* Function definition */{

int i, total; 

for(i=0,total=0;i<5;i++) /* Calculates the sum */total+=num_arr[i];

 return total; /* Returns the sum to main() */

}

Sample output of the program

Enter number 1: 5 Enter number 2: 10 Enter number 3: 13 Enter number 4: 26 Enter number 5: 21 The sum of the array

is 75

Page 63: Advance  topics of C language

#include<stdio.h>#include<string.h> void main(){char lines[5][20];int ctr, longctr=0;int longest(char lines_arr[][20]); /* Function declaration */

  clrscr();  for(ctr=0;ctr<5;ctr++)

/* Accepts string values into the array */{

printf("\nEnter string %d: ", ctr+1);scanf("%s", lines[ctr]);

}

Passing string to function (example)

Page 64: Advance  topics of C language

Passing string to function (example)

longctr=longest(lines);/* Passes the array to the function */

 printf("\nThe longest string is %s", lines[longctr]);

 getch();

} int longest(char lines_arr[][20]) /* Function definition */{

int i=0, l_ctr=0, prev_len, new_len; 

prev_len=strlen(lines_arr[i]);/* Determines the length of the first element */

 

Page 65: Advance  topics of C language

Passing string to function (example)

for(i++;i<5;i++){

new_len=strlen(lines_arr[i]);/* Determines the length of the next element */

 if(new_len>prev_len)

l_ctr=i; /* Stores the subscript of the longer string */ 

prev_len=new_len;}

 return l_ctr;/* Returns the subscript of the longest string */

}

Sample output of the program

Enter string 1: The Enter string 2: Sigma Enter string 3: Protocol Enter string 4: Robert Enter string 5: Ludlum The longest string is Protocol

Page 66: Advance  topics of C language

Structures • Structure is another user defined data type which

allows you to combine data items of different kinds.

• The variables in a structure can be of different types: Some can be int, some can be float, and so on.

• The data items in a structure are called the members of the structure.

Page 67: Advance  topics of C language

Defining the Structure

Page 68: Advance  topics of C language

Declaring Structure Variables

• struct part part1;

• defines a variable, called part1, of type structure part.

• This definition reserves space in memory for part1.

Model no part no cost

10031001 1007 1011

part1

Page 69: Advance  topics of C language

Declaring Structure Variables

• Other ways of declaring structures variables:struct stud{

char name[10];int age;};

main(){struct stud s1, s2;

}

struct stud{

char name[10];int age;} s1, s2;

main(){}

struct {

char name[10];int age;} s1 s2;

main(){

}

Page 70: Advance  topics of C language

Accessing Structure Members

• Members can be accessed using something called the dot operator. syntax is

Structure_var_name.element_name;• Here’s how the first member is given a value:

part1.modelnumber = 6244;

• .Is called member access operator

Page 71: Advance  topics of C language

Initializing Structure Members

• Initializer listspart part1= { 6244, 373, 217.55 };

• Assignment statementspart part1;part1.modelnumber = 6244;part1.partnumber = 373;Part1.cost = 217.55;

part part2; //define variable part2 = part1;

Page 72: Advance  topics of C language

Example

Page 73: Advance  topics of C language

Nested structureStructures can also be nested in such a way that an element of a structure is itself another structure:

struct subject{char name[20];float marks;};

struct friend {char name[10];int age;subject fsub;}

Int main(){friend frnd1,frnd2;frnd1.name=“amir”;frnd2.name=areeb;

frnd1.fsub.name=“computer”;frnd2.fsub.name=“maths”;

frnd1.fsub.marks=85;frnd2.fsub.marks=80;}

Page 74: Advance  topics of C language

Passing Structures as Arguments

• A structure variable can be passed as an argument to a function

• This facility is used to pass groups of logically related data items together instead of passing them one by one

• The type of the argument should match the type of the parameter

Page 75: Advance  topics of C language

Example

Page 76: Advance  topics of C language

Array of Structures A common use of structures is in arrays of structures A structure is first defined, and then an array

variable of that type is declared Example:

struct student class_a[50];

To the access the variable author of the fourth element of the array books:

class_a[4].marks;

Page 77: Advance  topics of C language

Array of Structures • Structure arrays are initialized by enclosing the list of values of its

elements within a pair of braces • Example

struct unit { char ch;int i;

};

struct unit series [3] ={ {‘a’, 100}{‘b’, 200}{‘c’, 300}

};

Page 78: Advance  topics of C language

Array of Structures • Memory representation of arrays of structure

1001 1004 1007 1010

0 1 2

series

Ch i Ch i Ch i1002

1004

1005

1007

1008

1010

Page 79: Advance  topics of C language

Sorting Arrays• Sorting involves arranging the array data in a

specified order such as ascending or descending

• Data in an array is easier to search when the array is sorted

• There are two methods to sort arrays – Selection Sort and Bubble Sort

• In the selection sort method, the value present in each element is compared with the subsequent elements in the array to obtain the least/greatest value

Page 80: Advance  topics of C language

Bubble sort

Page 81: Advance  topics of C language

Example main(){int arr[] = {15,2,20,10,1}; int temp=0;

for (int i = 0; i < 5; i++) { for (int j = 0; j < 4; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } }

Page 82: Advance  topics of C language

Example I J arr[j] >

arr[j+1]Temp=arr[j]

arr[j]=arr[j+1] arr[j+1]=temp

0 0 arr[0]>arr[1]15 > 2 true

Temp=arr[0]Temp=15

0 1 arr[1]>arr[2]15 > 20 false

0 2 arr[2]>arr[3]20 > 10 true

Temp=arr[2]Temp=20

0 3 arr[3]>arr[4]20 > 1 true

Temp=arr[3]Temp=20

1 0 arr[0]>arr[1]2 > 15 false

1 1 arr[0]>arr[1]15 > 10 true

Temp=arr[1]Temp=15

15 2 20 10 10 1 2 3 4

arr

Page 83: Advance  topics of C language

Insertion sort

Page 84: Advance  topics of C language

Example main(){int arr[] = {15,2,20,10,1}; int temp=0;

for (int i = 1; i < max; i++) { int j = i;

while (j > 0) { if (arr[j - 1] > arr[j]) { int temp = arr[j -

1];

arr [j - 1] = arr[j];

arr[j] = temp; j--;

} else break; }}

}

Page 85: Advance  topics of C language

Example I J=

iJ>0 arr[j - 1] >

arr[j]Temp=arr[j-1]

arr[j-1]=arr[j]

arr[j]=temp

J--

1 1 1>0 true

arr[0]>arr[1]15 > 2 true

Temp=15 0

1 0>0 false

2 2 2>0 true

arr[1]>arr[2]15>20 false

While loop terminate

3 3 3>0 true

arr[2]>arr[3]20>15 true

temp=arr[2]temp=20

2

2>0 true

arr[1]>arr[2]15>10 true

temp=arr[1]temp=15

1

1>0 true

arr[0]>arr[1]2>15 false

While loop terminate 15 2 20 10

10 1 2 3 4

arr

Page 86: Advance  topics of C language

Filing All I/O operations in C are carried out using

functions from the standard library

This approach makes the C file system very powerful and flexible

I/O in C is unique because data may be transferred in its internal binary representation or in a human-readable text format

Page 87: Advance  topics of C language

Why files are needed?

• When the program is terminated, the entire data is lost in C programming. If you want to keep large volume of data, it is time consuming to enter the entire data. But, if file is created, these information can be accessed using few commands.

Page 88: Advance  topics of C language

Stream • Stream is not a hardware it is linear queue which

connect file to program and passes block of data in both direction .So it is independent of devices which we are using. We can also define stream as source of data. This source can be

• (a) A file• (b) Hard disk or CD, DVD etc.• (c) I/O devices etc.

Page 89: Advance  topics of C language

Stream • In c programming language there are two type of

stream.

(a) Text streams

(b) Binary streams

Page 90: Advance  topics of C language

Stream • A text stream is a sequence of characters that

can be organized into lines terminated by a new line character

Binary streams are a flat sequence of bytes, which do not have any flags to indicate the end of file or end of record

The end of file is determined by the size of the file

Page 91: Advance  topics of C language

File A file can refer to anything from a disk file to a

terminal or a printer

A file is associated with a stream by performing an open operation and disassociated by a close operation

When a program terminates normally, all files are automatically closed

When a program crashes, the files remain open