Date post: | 06-Apr-2017 |
Category: |
Education |
Upload: | mehwish-mehmood |
View: | 26 times |
Download: | 3 times |
M E H W I S H M E H M O O D
Overview of C Lang
Topics• Pointers• Malloc• Alloc• Calloc• Free• Realloc• Functions• Strings• Structures• Sorting• File handling
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?
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)
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
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’
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;
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
9
Dereferencing Operator (*)• Consider the following statements.
1. num = 78;
2. p = #
3. *p = 24;
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;
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.
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
• 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
Pointer to array
a &a[0]‘a’ is a pointer only to the first element, not the whole array
same
Dereferencing array pointers
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 */
}}
Output
Pointer to string
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.
Example
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
Example
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
Reallaoc()
Syntax:
void *realloc( void *ptr, size_t size );
Example
Example
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().
Example
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.
Function
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.
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
Functions without Return Value
(Only Have Side Effect)
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
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.
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
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
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
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
Storage Classes
• automatic
• external
• static
• register
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
Calling The Functions
Call by value
Call by reference
Pass by value
When arguments are passed to the called function, the values are passed through temporary variables
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
Nesting Function Calls
main(){
.
.
palindrome();..
}
palindrome(){
.
.getstr();reverse();cmp();..
}
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.
Function pointer
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.
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.
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);
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);
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
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
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
Example
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
Example
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
The strlen() function Determines the length
of a string
Syntax: strlen(str);
The function returns an integer value for the length of str
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);..
}
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]);
}
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
#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)
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 */
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
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.
Defining the Structure
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
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(){
}
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
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;
Example
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;}
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
Example
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;
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}
};
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
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
Bubble sort
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; } } }
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
Insertion sort
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; }}
}
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
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
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.
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.
Stream • In c programming language there are two type of
stream.
(a) Text streams
(b) Binary streams
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
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