Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
1
• To understand design concepts of fixed-length and variable-length strings
• To understand the design implementation of C-language delimited strings
• To write programs that can read, write and manipulate strings
• To write programs that use array of strings
• To write programs that parse a string into separate variable.
• To write programs that implement string functions by using the library
Strings
Objectives
2
String Concepts
• A string is a series of characters treated as a unit.
• Strings can be stored as fixed-length objects or variable-length objects
• String Taxonomy
String Taxonomy
3
• Reserves the fixed amount of memory for the string variable
• Disadvantages
1) Complete string can not be stored if the size is small
2) Memory is wasted if the size is too big
Ex:
Char a[10]=“hello”; // waste memory
String Concepts
Fixed length
Variable length
• Size of storage can be expanded and compressed to accommodate the data
• There are two common techniques to use length-controlled strings and delimited strings
4
String Concepts
• This type adds a count that specifies no. of characters in the string.
• This count is used by a string manipulating function to determine the actual length
Length controlled
Delimited String
• This type adds the delimiter at the end of the string. Most common
delimiter for string is „\0‟ . It is also called as null character
5
Strings in ‘C’ Language
A string in C is a variable-length array of characters that is delimited by
the null character‟\0‟.
• Storing Strings
• The String Delimiter
• String Literals
• Strings and Characters
• Declaring Strings
• Initializing Strings
• Strings and the Assignment Operator
• Reading and Writing Strings
Topics:
6
• String is stored in an array of character which is terminated by null character (\0)
• The name of the string is a pointer to the beginning of the string
Strings in ‘C’ Language
Storing strings
Storing Strings
Storing Strings and Characters
7
Strings in C
• A delimiter is required at the end of the string, because it is not a data type, it is a data structure, i.e., its implementation is logical , but not physical
• The physical structure is the array in which the string is stored
The String Delimiter
Differences Between Strings and Character Arrays
Strings in Arrays
• For storing a string, we need an extra space for null character , but it is not required for other type of arrays.
8
• A string literal is also known as string constant, which is a sequence of characters enclosed in double quotes (“ “).
• C automatically creates an array of characters to store string literal
Example: Char ar[10] = “helloworld”; Example: Difference between string literal and character literal.
Strings in C
String literals
Character Literals and String Literals
Example: How to print a particular character in string
String Literal Reference
9
Strings in C
• Character array is used to store strings
• In defining array to store a string, storage structure must be one byte larger than the maximum data size
• One extra byte is required to store delimiter(„\0‟)
Declaring a String
Defining Strings
• Syntax: Char str[11];//using char array for storing sring Char *str;//using pointer for storing string
10
Strings in C
Initializing String
• At the time of declaration of a string, if the value is assigned, it is called as string initialization
• Ex: Char str[10]=“helloworld”;//declaration+value=intialization
Initializing Strings
String and assignment operator
• assignment operator „=„ is used for assigning value to string variable
• Ex:
Char str[10];//declaration
Str=“helloworld”;//assign value using assignment opr
Turbo c example17.c with error simulation
• Types of Array of String
1) ONE DIMENSIONAL ARRAY OF STRINGS
2) TWO DIMENSIONAL ARRAY OF STRINGS
• ONE DIMENSIONAL ARRAY OF STRINGS
this can be initialized as follows:
type variable-name[];
• char a[10]; // declaration of an array
• char b[20] = “Andhra pradesh”; // initialization of an array
Arrays of characters (1 of 3)
Unit No:4
Lecture No:L52
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
• TWO DIMENSIONAL ARRAY OF STRINGS It is also referred as table of strings. This can be
initialized as follows: type variable-name[][]; • char a[10][10]; // declaration of 2-D array • char b[2][2] = { “Andhra pradesh”,; // initialization of 2-D
array “ Karnataka”};
• The first subscript gives the number of names in the array. • The second subscript gives the length of each item of the
array. • .
Variable length character strings(2 of 3)
• Example:
• char list[6][10]={ “akshay”, “parag”,“raman”,“srinivas”,
• “gopal”,“rajesh”};
• The names would be stored in the memory as shown in the below figure
• Example: Two dimensional arrays of strings
13
Arrays of Strings (3 of 3)
Turbo c example 22 with error simulation
14
Inputting character strings
• C provides two basic ways to read and write strings.
1) Formatted input functions: scanf/fscanf
2) Formatted output functions: printf/fprintf.
• Special set of string-only functions: get string (gets/fgets) and
put string (puts/fputs)
15
• scanf( ) and fscanf( ) are used for reading a string • Both predefined functions are available in <stdio.h>
• Both functions use control string %s for reading the string
Formatted String Input
Formatted string input
scanf():
• It is used to read string from standard input device i.e., keyboard • It omits any leading whitespaces • It ends the string by using null character‟\0‟
syntax:
scanf(“control string”, var1,var2……); Ex: scanf(“%s”,x);
16
fScanf()
• The function fscanf() reads the data from a given file stream in a manner exactly like scanf(). The return value of fscanf() is the number of variables that are actually assigned with values.
syntax:
#include <stdio.h>
int fscanf( FILE *stream, const char *format, ... );
Ex:
1)char name[20] = "Mary";
2)FILE *in;
3)in = fopen( “test.txt", “r" );
4)fscanf( in, “ %s", name );
Formatted String Input
• To implement fscanf (), open the file in read mode as shown in step-3
• use fscanf() to read the string from the file. It stores the string value in a variable called „name‟ as shown in step-4
17
• printf ( ) and fprintf ( ) are used for writing the stings
• Both functions are predefined in <stdio.h>
• Both functions use control string %s for string writing
Formatted String output
Formatted string output functions
Printf():
• It is used to print the string on standard output device such as monitor
• Uses justification flag(-) for left justification
• Sets the minimum width for string in printf
• Sets precision for string in printf in order to specify the maximum number of characters to be printed
syntax
printf(“control string”, var1,var2……);
Ex: printf(“%s”,x); Turbo c example18&19 with error simulation
18
Formatted String output
fprintf():
• The function fprintf() writes data to the given file stream . The return value of fprintf() is the number of variables that are actually assigned values.
syntax:
#include <stdio.h>
int fprintf( FILE *stream, const char *format, ... );
Ex:
1)char name[20] = "Mary";
2)FILE *in;
3)out = fopen( “test.txt", “w" );
4)fprintf( out, "Hello %s\n", name );
• To implement fprintf open the file in write mode as shown in step-3
• Use fprintf() to write the string to a file. It stores the string in the file, „test.txt. as shown in step-4
19
String Input/output Functions
• gets ( ) and fgets ( ) are used to read only strings and these functions do not need control string „%s‟
• Gets ( ) reads data from standard input device and fgets reads data from the file. Both are terminated by new line character‟\n‟ and assign a null character(„\0‟) at the end of the string
• Unlike scanf() and fscanf(), gets() reads a line of string at a time. It is also called as line to string input functions
Special set of string-only functions for input
Syntax:
Char * gets(char* strptr);
Char *fgets(char *strptr,int size ,flie *sp);
20
String Input/output Functions
Example: gets ( ) and fgets () function
• As shown in the figure above, gets and fgets doesn‟t work in the same way.
• Gets convert the new line character into null character‟\0‟. While fgets puts new line character and appends the null character at the end of the string
21
• puts ( ) and fputs ( ) are used to write only string data type. Both functions do not require control string %s to print a string.
• puts() writes data to standard output device and fputs() writes data to the file
• Both functions write until the null character ‟\0‟ • Unlike printf and fprintf, a line of string can be written at a time using puts()
and fputs(). It is also called as string to line output functions
String output Functions
Special set of string-only functions for output
Syntax:
Int puts(const char* strptr);
Int fputs(const char *strptr,flie *sp);
22
String Input/output Functions
Example: puts ( ) and fputs ( ) function
Turbo c example20 &21 with error simulation
• As shown in figure above, puts and fputs doesn‟t work in the same way.
• Puts convert the new line character into null character ‟\0‟ while reading from memory.
• fputs drops null character at the end of the string while reading from memory.
• The C Library provides a rich set of string handling functions that
are declared in the header file <string.h>.
String Length
• This function counts and returns the number of characters in a string.
• Function declaration: int strlen(const char * string);
• It can be used as follows
n=strlen(string);
• n is an integer variable, which receives the length of the string. The counting ends at the null character.
• String length excludes the null character („\0‟)
• Turbo c example14 &15 with error simulation
String Handling functions (1 of 19)
Turbo c example 23&24with error simulation
Unit No:4
Lecture No:L54
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
Character library functions
Turbo c example 23&24with error simulation
Unit No:4
Lecture No:L53
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
Prototype Description
int isdigit( int c ) Returns true if c is a digit and false otherwise.
int isalpha( int c ) Returns true if c is a letter and false otherwise.
int isalnum( int c ) Returns true if c is a digit or a letter and false otherwise.
int isxdigit( int c ) Returns true if c is a hexadecimal digit character and false otherwise.
int islower( int c ) Returns true if c is a lowercase letter and false otherwise.
int isupper( int c ) Returns true if c is an uppercase letter; false otherwise.
int tolower( int c ) If c is an uppercase letter, tolower returns c as a lowercase letter. Otherwise, tolower
returns the argument unchanged.
int toupper( int c ) If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise, toupper
returns the argument unchanged.
int isspace( int c ) Returns true if c is a white-space character—newline ('\n'), space (' '), form feed
('\f'), carriage return ('\r'), horizontal tab ('\t'), or vertical tab ('\v')—and
false otherwise
int iscntrl( int c ) Returns true if c is a control character and false otherwise.
int ispunct( int c ) Returns true if c is a printing character other than a space, a digit, or a letter and false
otherwise.
int isprint( int c ) Returns true value if c is a printing character including space (' ') and false
otherwise.
int isgraph( int c ) Returns true if c is a printing character other than space (' ') and false otherwise.
String copy
• There are two types of string copy function:
1. Basic String copy
2. String copy - length controlled
Basic String copy
• Strcpy() copies the contents of the string including the null character to the string.
• General form of the Function:
strcpy(destination string, source string);
• It can be used as follows :
strcpy(string1,string2);
• Assigns the contents of string2 to string1. String2 may be a character array variable or a string constant.
String Manipulation functions (2 of 19)
String Manipulation functions (3 of 19)
Example: String copy
Turbo c example 25&26 with error simulation
String copy-length controlled
• Strncpy function contains a parameter that specifies the maximum number of characters that can be moved at a time.
• General form of the Function:
• strncpy (destination string, source string, int size);
String Manipulation functions (4 of 19)
Note: It is recommended to use strncpy to copy one string to another in case of restricted length
Example: String number copy
String compare
• There are two categories of string compare functions:
1. strcmp 2. Strncmp
strcmp
• Strcmp() compares two strings until it reaches unequal characters or when it reaches to the end of the string.
Declaration: • int strcmp(string1, string 2);
• It can be used as follows
strcmp(str1,str2); • If ''str1'' is less than ''str2'„, then, it returns a value which is less
than 0
• If ''str1'' is greater than ''str2'„, then, it returns a value which is greater than 0
• If ''str1'' is equals to ''str2'„, then it returns 0. Example:strcmp(name1,name2);strcmp(name1,”John”);strcmp(“their”,”there”);
String Manipulation functions (5 of 19)
String Manipulation functions (6 of 19)
Example: String Compares
Turbo c example 27&28 with error simulation
Unit No:4
Lecture No:L55
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
Strncmp
• The string number compare function,strncmp,tests two strings for a specified maximum number of characters(size).
• The general form of the function:
• int strncmp(string 1, string 2, int size);
• The table below compares two strings using the strncmp function for various sizes
Results for string compate
String Manipulation functions (7 of 19)
String concatenate
• String concatenate functions append one string to the end of another.
• The function returns the address pointer to the destination string.
• 1.Basic string concatenation: strcat
• Function declaration: strcat(string1, string2);
• 2.String concatenation-Length controlled: strncat
• Function declaration : strncat(string1, string2, int n);
String Manipulation functions ( 8 of 19)
Turbo c example 29&30 with error simulation
• Example:String concatenate
32
String Manipulation functions ( 9 of 19)
• String reverse
String reverse function,Reverses the contents of the string. The general form of the function: strrev(string); Example: #include<stdio.h>
#include<string.h>
void main()
{ char s[]=”hello”;
strrev(s); puts(s);
getch();
}
33
String Manipulation functions ( 10 of 19)
Turbo c example 31 with error simulation
Additional material :
Searching a character in a String
• There is a need to find the location of a character in a string.
• There are two string functions which can be used to search for a character in a string.
1. strchr
2. strrchr
• The declarations for these functions are shown below:
• strchr(string 1, int ch);
• strrchr(string1, int ch);
String Manipulation functions (11 of 19)
String Manipulation functions (12 of 19)
Example: Character in (strchr)
Search for a substring
• Locates a string in a string
• General function declaration :
strstr ( string 1, sub_string);
String Manipulation functions (13 of 19)
Example: string in string
Turbo c example 32 with error simulation
• Search for a character in a set
Basic string span
strspn() searches the string by spannig characters that are in the set
and stopping at the first character that is not in the set.
The function declaration is shown in below:
int strspn(string, “character_set”);
Example: string span
String Manipulation functions (14 of 19)
Complemented string span
• strcspn, is string complement span; its function stops at the first character that matches one of the characters in the set.
• General form of the function :
int strcspn (string, “string_set”);
string-pointer
• Strpbrk () returns a pointer to the first character found in the set
• General form of the function:
int strpbrk(string,”string_set”);
string token
• The string token strtok() is used to locate the substrings, called tokens, in a given string.
• General form of the function:
strtok(string, delimiters);
String Manipulation functions (15 of 19)
String Manipulation functions (16 of 19)
Example: Parse a simple string
1) String to long
• String to long function, strtol, converts a string to a long integer
• General from of the function:
long strtol(char* str,char** ptr,int base);
2) String to double
• String to double functions, strlod() and wcstod() are similar to string to long functions, except that they do not have base.
• General form of the function:
double strtod(char* str,char** ptr);
String Manipulation functions (17 of 19)
String to Number
String Manipulation functions (18 of 19)
Example: String to number functions
Unit No:4
Lecture No:L56
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
String Manipulation functions (19 of 19)
Example: Parsing with string Token
String/Data Conversion (1 of 3)
• A common set of applications format data either by converting a sequence of characters into corresponding data types or vice versa.
• Two such applications are parsing and telecommunications.
1) String to Data Conversion
2) Data to string Conversion
String to Data Conversion
• The string scan function is called sscanf().
• This function scans a string as though the data were coming from a file.
• The general form of the function:
int sprintf( char * out_string, const char * format_string, ---);
String/Data Conversion (2 of 3)
sscanf operation
Data to String Conversion
• The string function sprintf() follows rules of fprintf.
• General form of the function:
int sprintf( char * out_string,const char * format_string,---);
Example: sprintf operation
String/Data Conversion (3 of 3)
46
Pointers
Objectives
• To understand the concept and use of pointers
• To be able to declare, define and initialize pointers
• To write programs that access data through pointers
• To pass pointers as parameters
• To understand pointer compatibility, especially regarding pointers to pointers
Unit No:4
Lecture No:L57
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
47
Pointer basics
• A pointer is a constant or variable contains an address that can be used to access data.
• Pointers are special variables that can hold the address of another variable.
• Pointer has a name and a location, both of which are constant
Unit No:4
Lecture No:L58
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
• Computers store data in memory slots
• Each slot has an unique address
• Variables store their values as shown in the below table:
48
Addr Content Addr Content Addr Content Addr Content
1000 i: 37 1001 j: 46 1002 k: 58 1003 m: 74
1004 a[0]: ‘a’ 1005 a[1]: ‘b’ 1006 a[2]: ‘c’ 1007 a[3]: ‘\0’
1008 ptr: 1001 1009 … 1010 1011
Computer Memory
• pointer (ptr) is a variable that stores address of another variable, which refers to a memory location
• Pointers do not store the actual value of the variable
Example:
49
int i = 5;
int *ptr; /* declares a pointer ptr to an
integer variable*/
ptr = &i;/*stores address of i
to ptr*/
printf(“i = %d\n”, i);
printf(“*ptr = %d\n”, *ptr);
printf(“ptr = %u\n”, ptr);
5 i
address of i ptr
Output:
i = 5
*ptr = 5
ptr = 644345
value of ptr =
address of i
in memory
Addressing Concept
50
Pointer Declaration
• * is a unary operator (also called indirection operator)
• Indirection (dereferencing of a pointer) specifies that the pointer value is to be used to reference (address) another variable.
• A pointer is declared as :
<pointer type> *<pointer-name>
• pointer-type : It specifies the type of pointer. It can be int , char, float
etc. The type specifies the type of pointer variable.
• pointer-name : It can be any name specified by the user.
51
Pointer Declaration
52
Pointer Declaration
Example:
Variables Pointers
• One of the most common causes of errors in programming is uninitialized pointers.
• These errors are difficult to debug because the effect of error is not found until the program execution.
• Example of an uninitialized variable and an uninitialized pointer.
53
Initialization of Pointer Variables
• A pointer variable must be assigned a valid memory address.
• <pointer declaration> <name-of-pointer> = <address of a variable>
int a; // int variable value unknown
int *p = &a; // p has a valid address
*p = 89; // a is assigned value 89
54
Initialization of Pointer Variables
Turbo c example1.c with error simulation
• * (Indirection operator) is used to access variable through pointer.
• Indirection operator is a Unary operator whose operand must be a pointer value.
• The result of above is an expression that can be used to access the pointed variable for the purpose of inspection or alternation.
• To access the variable „‟a” through the pointer p, p is declared as *P and p is initialized as p=&a
• Example: add 1 to the variable “a” can be done with any of the following statements:
• a++1 a=a+1 *1=*1+1 *p++
55
Accessing variables through Pointer
Note
A pointer that does not point to any variable, it contains NULL.
Turbo c example2.c with error simulation
56
Accessing variables through Pointer
A few advantages:
- Pointers allow you to implement sharing without
copying
- Pointers allow modifications by a function that is
not the creator of the memory i.e. function A can
allocate the memory and function C can modify it,
without using globals, which is a no-no for safe
programming.
- Pointers allow us to use dynamic memory
allocation.
57
Pointer Arithmetic
• Arithmetic operations can be performed on pointers
– Increment/decrement pointer (++ or --)
– Add an integer to a pointer( + or += , - or -=)
– Pointers may be subtracted from each other
– Operations meaningless unless performed on an array
Unit No:4
Lecture No:L59
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
58
Pointer Arithmetic
• 5 element int array on machine with 4 byte ints
– vPtr points to first element v[ 0 ]
• at location 3000 (vPtr = 3000)
– vPtr += 2; sets vPtr to 3008
• vPtr points to v[ 2 ] (incremented by 2), but the machine has 4 byte ints, so it points to address 3008
pointer variable vPtr
v[0]
v[1]
v[2]
v[4]
v[3]
3000
3004
3008
3012
3016
location
59
Pointer Arithmetic
• Subtracting pointers
– Returns number of elements from one to the other. If vPtr2 = v[ 2 ];
vPtr = v[ 0 ];
– vPtr2 - vPtr would produce 2
• Pointer comparison ( <, == , > )
– See which pointer points to the higher numbered array element
– Also, see if a pointer points to 0
60
Pointer Arithmetic
• Pointers of the same type can be assigned to each other
– If not the same type, a cast operator must be used
– Exception: pointer to void (type void *)
• Generic pointer, represents any type
• No casting needed to convert a pointer to void pointer
• void pointers cannot be dereferenced
61
Pointers to Pointers,
generic pointers
• Pointers to Pointers are necessary for manipulating advanced data structures
• Pointers that point to other pointers are called Pointers to Pointers
• Example: a pointer pointing to an integer pointer.
Introduction
• Above example demonstrates two levels of redirection
• Many applications may require two or more levels of redirection
• Each level of redirection requires a separate indirection operator.
Unit No:4
Lecture No:L60
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
• Suppose a pointer „p1′ points to another pointer „p2′ that points to
a character „c‟. In memory, the three variables can be visualized as :
• In memory, pointer p1 holds the address of pointer p2. Pointer p2
holds the address of character „c‟.
• Pointer p1 is declared as *p1
• Pointer to Pointer is declared as **p2
62
Pointers to Pointers
Turbo c example4.c with error simulation
63
• Pointers have a type associated with them, such as char, int, float,
etc.
• Each pointer takes on the attributes of the type to which it refers to
in addition to its own attributes.
• Compatibility types are:
a) Pointer Size Compatibility
b) Dereference Type Compatibility
c) Dereference Level Compatibility
Compatibility
Introduction
Pointer Size Compatibility
64
• The size of all pointers is the same.
• Every pointer variable holds the address of one memory location in the computer.
• On the other hand, the Size of the variable that the pointer references can be different.
• The pointer also takes the attributes of the type being referenced.
Example: Prints the size of each pointer and the size of each referenced variable.
Compatibility (1/3)
• Turbo c exp5.c with error simulation
Dereference Type Compatibility
65
• The dereference type is the type of the variable that the pointer is referencing.
• It is invalid to assign a pointer of one type to a pointer of another type.
• A pointer to a char is only compatible with a pointer to a char.
• A pointer to an int is only compatible with a pointer to an int.
• Do not assign a pointer to a char to a pointer to an int.
• The exception to the reference type compatibility rule is the pointer to Void (A void pointer cannot be dereferenced).
Compatibility
Example
Casting Pointers
• The problem of type incompatibility can be solved by using casting.
• An explicit assignment between incompatible pointer types is done
by using a cast operator.
• For example,
• pc=(char *)&a; /*pc is a character pointer and a is a integer pointer */
• This converts an integer pointer to a char and assigns the value to pc.
66
Compatibility
Dereference Type Compatibility
• Turbo c exp6.c with error simulation
Dereference Level Compatibility
• A pointer to int is not compatible with a pointer-to-pointer to int.
• The pointer to int has a reference type of int, while a pointer-to-pointer to int has a reference type of pointer to int.
67
Compatibility
Example
68
Pointer Applications
Pointer is used for different purposes. Pointer is low
level construct in programming which is used to
perform high level task.
Some of the pointer applications are listed below
1. Passing Strings to function
2. Provides effective way of implementing
the different data structures such as trees, graph,
linked list
69
Array of Pointers
Since a pointer is a variable type, we can create an array of pointers just like we can create any array of any other type.
Although the pointers may point to any type, the most common use of an array of pointers is an array of char* to create an array of strings.
70
• Array name can be used as pointer variable
• The base address of array is assigned to the pointer variable
• Base address of an array specifies the address of the first element in the array
• By using pointer arithmetic, other elements of the array can be accessed.
Arrays and Pointers
Unit No:4
Lecture No:L61
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
71
Example: Int *ptr; Int a[4]={1,3,4}; ptr=&a[0] //assigning the base address of an array to a pointer or ptr=a; //assigning the base address of an array to a pointer
Array and Pointers
• The pointer variable prt points to the first element of an array as shown in the figure
1
3
4
0
1290 1290
1292
1294
1296
array
ptr
72
• To access other elements in an array, pointer arithmetic with restricted set of pointer operators can be used.
• First, pointer is assigned to the base address of an array using its name.
• ptr is a pointer and “a” is base address of array a[5]
• ptr+1 points to the second element of an array i.e a[1]
Pointer arithmetic and array:
Array and Pointers
Turbo c example11.c
with error simulation
73
<type> *<name>[number-of-elements];
For example :
char *table[6];
or
<type> **<name>;
For example :
char **table;
Array of Pointers
syntax for array of pointer
other way of Declaring array of pointers:
74
shows how Arrays are stored in memory location
Array of Pointers
Example: Array of pointer
Turbo c example 12 &13 with error simulation
75
A common use of an array of pointers is to create an array of strings. The declaration below creates an initialized array of strings (char *) for some boys names. The diagram below illustrates the memory configuration.
char *name[] = { “Bobby”, “Jim”,
Harold” };
B o b b y \0
J i m \0
H a r o l d \0
names:
0
1
2
Ex: Names
76
• Pointer to void is generic pointer that can be used to represent any data type during compilation or run time
• Pointer to void is not a null pointer
• It is pointing to generic pointer data type void
• A pointer to void can be assigned without type casting
Pointer to void-Generic pointer
77
Void *ptr;
Int x=10;
Float y=12.4;
ptr=&x;
ptr=&y;
Pointer to void
Syntax: Example
Turbo c example14.c with error simulation
78
Functions returning pointers
• Inter function Communication constitutes the following:
a) Downward Communication
b) Upward Communication
c) Bi-direction Communication
• Downward Communication uses pass-by-value
• Pass-by-address is used for both Upward and bi-direction communication
• Pass-by-address can be effectively implemented by passing a pointer.
• As such, one of the most useful applications of pointers is in implementation of inter function communication.
Introduction
Unit No:4
Lecture No:L62
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
79
Pointers for Inter function Communication (1/2)
Passing Addresses
• Exchange function- passing of two variables whose values are to be exchanged.
• call by value used in the following example. The data is exchanged in the called function but no changes to the calling program.
• Instead of passing data to the called function, pointer is used to pass the address.
An unworkable Exchange
• Pointers can be used to pass addresses of variables to called functions, thus allowing the called function to alter the values. (This is known as call by reference, since we are referencing the variables)
• Example shows the swap function modified from call by value to call be reference.
80
Pointers for Inter function Communication (2/2)
Passing Addresses
Turbo c example3.c with error simulation
81
Pointers for Inter function Communication
Functions Returning Pointer
• A called function can also return a pointer.
Example: Pointer to the smaller of two variables a and b.
• When a pointer is returned, it must point to data in the calling function.
• It is an error to return a pointer to a local variable in the called function
82
Pointer to function
• Function in a program occupy memory
• Name of the function is a pointer constant that refers to the starting address of the function in the memory
• Example: Four functions stored in memory: main, fan, pun and sum.
83
Pointer to function
• Like other pointer types, pointers to function variable can also be defined.
• Pointer to function will store the address of the function.
Syntax for declaring pointer to function:
Data type (*fptr) (par1,par2);
84
Pointer to function
• Syntax for declaring pointer to function:
fptr=function name
Example:
fptr=sum // sum is function name
Syntax for calling function using pointer:
variable=(*fptr)(par1-val,par2-val);
Example:
Y=(*p)(2,3);
Turbo c example15.c with error simulation
85
Command Line Arguments
• Command line arguments are passed to your program as parameters to main.
int main( int argc, char *argv[ ] )
– argc is the number of command line arguments (and hence the size of argv)
– argv is an array of strings which are the command line arguments. Note that argv[0] is always the name of your executable program.
86
Command Line Arguments
• For example, typing myprog hello world 42 at the linux prompt results in – argc = 4 – argv[0] = “myprog” – argv[1] = “hello” – argv[2] = “world” – argv[3] = “42”
• Note that to use argv[3] as an integer, you must convert if from a string to an int using the library function atoi( ). E.g. int age = atoi( argv[3] );
87
Memory Usage
Static Memory Allocation
Dynamic Memory Allocation
Memory Allocation Functions
Releasing Memory (free)
Topics to be discussed in this section:
Dynamic Memory allocation
Unit No:4
Lecture No:L63
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
88
Memory Allocation
• Memory allocation can be done either statically or dynamically.
• Static Allocation: Memory is allocated at compile time
• Dynamic Allocation: Memory is allocated at run time
Memory allocation functions
• Conceptually memory is divided into program memory and Data Memory.
• Program memory consists of the memory that is used for main() and all called functions.
• Data memory consists of global data and declarations .
• The stack memory contains the local variables of the function.
• Heap memory is unused memory allocated to the program and available during its execution.
89
Memory Usage
A Conceptual View of Memory
Note: We can refer to memory allocated in the heap only through a pointer.
• Four Memory management functions are used with dynamic memory.
• Functions malloc(), calloc(), realloc() are used for memory allocation.
• free() is used to return memory when memory is no longer needed.
• All the above memory management functions are available in the standard library file (stdlib.h).
90
Memory allocation functions
Memory Management Functions
• The malloc() function allocates a block of memory that contains the number of bytes specified in its parameter.
• returns a void pointer to the first byte of the allocated memory.
• The malloc() function is declared as : void *malloc(size_t size);
• Ex: pInt=malloc(sizeof(int));
• malloc() returns the address of the first byte in the memory space allocated, otherwise returns a NULL pointer, if it is not successful.
91
Malloc()
• An attempt to allocate memory from the heap when memory is insufficient is known as overflow.
• Turbo c exp7.c with error simulation
• calloc() (contiguous memory allocation) function is primarily used to allocate memory for arrays.
• It sets memory to null characters, by differing malloc().
• The calloc() function is declared as :
• void *calloc(size_t element_count,size_t element_size);
92
Calloc()
• Turbo c exp8.c with error simulation
Unit No:4
Lecture No:L64
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
• The realloc() function changes the size of the memory block by deleting or extending the memory at the end of the block.
• The realloc() function is declared as :
• void *realloc(void *ptr,size_t newsize);
93
Realloc()
• Turbo c exp9.c with error simulation
• When memory locations allocated by malloc(),calloc(),realloc() are no longer needed, they should be freed by using the function free().
• The free() function is declared as : void free(void *ptr);
• The following figure shows two examples .The first one releases memory allocated with malloc() and second releases memory for 200 elements allocated by calloc().
94
Releasing Memory(free)
Note: 1) Using a pointer after its memory has been released is a common programming
error. Guard against it by clearing the pointer. 2) The pointer used to free memory must be of the same type as the pointer used to allocate the memory.
• Turbo c exp10.c with error simulation