Unit - Iii: Malla Reddy Engineering College For Women
Unit - Iii: Malla Reddy Engineering College For Women
UNIT - III
Pointers – Introduction (Basic Concepts),
Pointers for inter function communication
pointers topointers,
compatibility
Pointer Applications-Arrays and Pointers, Pointer Arithmetic andarrays
Passing an array to a function
memory allocation functions
array of pointers,
programming applications, pointers to void, pointers to functions.
Strings – Concepts, C Strings
String Input / Output functions
arrays of strings,
string manipulation functions,
string / data conversion, C program examples.
POINTERS :
One of the powerful features of C is ability to access the memory variables by their
memory address. This can be done by using Pointers. The real power of C lies in the proper
use of Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say
that a pointer points to a variable that is stored at that address. A pointer itself usually
occupies 4 bytes of memory (then it can address cells from 0 to 232-1).
Advantages of Pointers :
1. A pointer enables us to access a variable that is defined out side the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
Definition :
A variable that holds a physical memory address is called a pointer variable or
Pointer.
Declaration :
Datatype * Variable-name;
The operator & returns the memory address of variable on which it is operated, this is
called Referencing.
int *p,x; x
=5; p= &x;
Assume that x is stored at the memory address 2000. Then the output for the
Output
Printf(“The Value of x is %d”,x); 5
Printf(“The Address of x is %u”,&x); 2000
Printf(“The Address of x is %u”,p); 2000
Printf(“The Value of x is %d”,*p); 5
Printf(“The Value of x is %d”,*(&x)); 5
#include <stdio.h>
void bad_swap(int x, int y);
void good_swap(int *p1, int *p2);
main() {
int a = 1, b = 999;
printf("a = %d, b = %d\n", a, b);
bad_swap(a, b);
printf("a = %d, b = %d\n", a, b);
good_swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
}
When an array is declared, elements of array are stored in contiguous locations. The
address of the first element of an array is called its base address.
Now both a and a[0] points to location 2000. If we declare p as an integer pointer, then we
can make the pointer P to point to the array a by following assignment
P = a;
We can access every value of array a by moving P from one element to another.
i.e., P points to 0 th element
P+1 points to 1st element
P+2 points to 2 nd element
P+3 points to 3 rd element
P +4 points to 4th element
The process of passing the actual value of variables is known as Call by Value.The
process of calling a function using pointers to pass the addresses of variables is known as Call
by Reference. The function which is called by reference can change the value of the variable
used in the call.
#include<stdio.h>
main()
{
int a,b; a =
10; b = 20;
swap (&a, &b); printf(“After
Swapping \n”);
printf(“a = %d \t b = %d”, a,b);
}
void swap(int *x, int *y)
{
int temp; temp
= *x; *x = *y;
*y = temp;
}
ADDRESS ARITHIMETIC :
We can add and subtract integers to/from pointers – the result is a pointer to another element
of this type
NULL POINTER :
‘Zero’ is a special value we can assign to a pointer which does not point to anything
most frequently, a symbolic constant NULL is used. It is guaranteed, that no valid address is
equal to 0.The bit pattern of the NULL pointer does not have to contain all zeros usually it
does or it depends on the processor architecture. On many machines, dereferencing a NULL
pointer causes a segmentation violation.
if (psz1)
/* use psz1 */
sizeof(psz1) // doesn't give you the number of elements in psz1. Need
additional size variable.
VOID POINTER :
In C ,an additional type void *(void pointer) is defined as a proper type for generic
pointer. Any pointer to an object may be converted to type void * without loss of
information. If the result is converted back to the original type ,the original pointer is
recovered .
Ex:
main()
{
void *a; int
n=2,*m;
double d=2.3,*c;
a=&n;
m=a;
printf(“\n%d %d %d”,a,*m,m);
a=&d;
c=a;
printf(“\n%d %3.1f %d”,a,*c,c);
}
In the above program a is declared as a pointer to void which is used to carry the address of
an int(a=&n)and to carry the address of a double(a=&d) and the original pointers are
recovered with out any loss of information.
POINTERS TO POINTERS :
So far ,all pointers have been pointing directely to data.It is possible and with
advanced data structures often necessary to use pointers to that point to other pointers. For
example,we can have a pointer pointing to a pointer to an integer.This two level indirection
is seen as below:
//Local declarations
int a;
int* p; int
**q;
q p a
Ex:
234560 287650 58
There is no limit as to how many level of indirection we can use but practically we
seldom use morethan two.Each level of pointer indirection requires a separate indirection
operator when it is dereferenced .
In the above figure to refer to ‘a’ using the pointer ‘p’, we have to dereference it as
shown below.
*p
To refer to the variable ‘a’ using the pointer ‘q’ ,we have to dereference it twice toget
to the integer ‘a’ because there are two levels of indirection(pointers) involved.If we
dereference it only once we are referring ‘p’ which is a pointer to an integer .Another way to
say this is that ‘q’ is a pointer to a pointer to an integer.The doule dereference is shown
below:
**q
In above example all the three references in the printf statement refer to the variable ‘a’. The
first printf statement prints the value of the variable ‘a’ directly,second uses the pointer
‘p’,third uses the pointer ‘q’.The result is the value 58 printed 3 times as below
58 58 58
Dynamic memory allocation uses predefined functions to allocate and release memory
for data while the program is running. It effectively postpones the data definition ,but not the
declaration to run time.
To use dynamic memory allocation ,we use either standard data types or derived types
.To access data in dynamic memory we need pointers.
Four memory management functions are used with dynamic memory. Three of
them,malloc,calloc,and realloc,are used for memory allocation. The fourth ,free is used to
return memory when it is no longer needed. All the memory management functions are found
in standard library file(stdlib.h).
BLOCK MEMORY ALLOCATION(MALLOC) :
The malloc function allocates a block of memory that contains the number of bytes
specified in its parameter. It returns a void pointer to the first byte of the allocated memory.
The allocated memory is not initialized.
Declaration:
void *malloc (size_t size);
The type size_t is defined in several header files including Stdio.h. The type is usually
an unsigned integer and by the standard it is guaranteed to be large enough to hold the
maximum address of the computer. To provide portability the size specification in malloc’s
actual parameter is generally computed using the sizeof operator. For example if we want to
allocate an integer in the heap we will write like this:
Pint=malloc(sizeof(int));
Malloc returns the address of the first byte in the memory space allocated. If it is not
successful malloc returns null pointer. An attempt to allocate memory from heap when
memory is insufficient is known as overflow.
The malloc function has one or more potential error if we call malloc with a zero size,
the results are unpredictable. It may return a null pointer or it may return someother
implementation dependant value.
Ex:
If(!(Pint=malloc(sizeof(int)))) //
no memory available
exit(100);
//memory available
…
In this example we are allocating one integer object. If the memory is allocated
successfully,ptr contains a value. If does not there is no memory and we exit the program
with error code 100.
REALLOCATION OF MEMORY(realloc):
The realloc function can be highly inefficient and therefore should be used
advisedly. When given a pointer to a previously allocated block of memory realloc
changes the size of the block by deleting or extending the memory at the end of the
block. If the memory can not be extended because of other allocations realloc
allocates completely new block,copies the existing memory allocation to the new
location,and deletes the old allocation.
Ptr
Before
18 55 33 121 64 1 90 31 5 77
10 Integers
New
Ptr=realloc(ptr,15*sizeof(int)); elements
not
initialized
ptr
18 55 33 121 64 1 90 31 5 77 ? ? ? ? ?
15 Integers
After
Releasing Memory(free):When memory locations allocated by malloc,calloc or realloc are no
longer needed, they should be freed using the predefined function free. It is an error to free
memory with a null pointer, a pointer to other than the first element of an allocated block, a
pointer that is a different type then the pointer that allocated the memory, it is also a potential
error to refer to memory after it has been released.
ptr ptr
Before After
Free(ptr);
BEFORE AFTER
… …
Free(ptr);
In the above example the 200 elements were allocated with calloc. When we free the
pointer in this case, all 200 elements are return to heap. First, it is not the pointers that are
being released but rather what they point to. Second , To release an array of memory that was
allocated by calloc , we need only release the pointer once. It is an error to attempt to release
each element individually.
Releasing memory does not change the value in a pointer. Still contains the address in
the heap. It is a logic error to use the pointer after memory has been released.
STRINGS
The group of characters, digits, and symbols enclosed with in double quotation marks are
called as strings.
Ex: “MRECW”
Every string terminates with „\0‟ (NULL) character. The decimal equivalent value of null
is zero. We use strings generally to manipulate text such as words and sentences. The
common operations that we can perform on strings are:
The last character of string is always „\0‟ (NULL). But it is not necessary to write „\0‟
character at the end of the string. The compiler automatically puts „\0\ at the end of the
string / character array.
The characters or elements of the string are stored in contiguous memory locations.
H E L L O \0
In this type also C compiler automatically inserts NULL character at the end of the string.
3. Char name[9]={{„H‟},{‟E‟},{‟L‟},{‟L‟},{‟O‟}};
In the above three formats we can initialize character arrays. We can also initialize
character array by using standard input functions like scanf( ), gets ( ) etc and we can
display strings by using puts ( ), printf ( ) functions.
The size of the character array: The argument / size of the character array or string =
Number of characters in the string + NULL character.
Note:
1. If NULL character is not taken in account then the successive string followed by the first
string will be displayed.
2. If we declare size of a string equal to the number of characters. i.e., without taking the
NULL character in to account and we print that will display some garbage value followed by
the string.
scanf(“%s”, name);
Limitation: If we use scanf ( ) function for reading string in runtime it terminates its input on
the first white space it finds. The scanf ( ) function automatically append NULL character at
the end of the input string, so we have to declare a (size of) character array which can
accommodate input string and NULL character.
(White space: blanks, tab space, carriage returns, new lines etc.)
We know that getchar ( ) function is used to read single character from the terminal. By using
this function repeatedly we can read successive single characters from the input and place
them into a character array (string). The reading is terminated when the user enters new line
character (\n) or press enter key. After reading the new line character this function
automatically appends NULL character at the end of the string in the place of new line
character.
i = i+1;
}
Using printf ( ) function we can display the string on output screen with the help of format
specifier „%s‟.
Ex: printf(“%s”,name);
We can use different format specifications to display strings in various formats according to
requirements.
Using puts ( ) function we can display the string without using any format specifier. This
function is available in the <stdio.h> header file in C library.
Using putchar ( ) function we can display one character at a time. So, by using this function
repeatedly with the help of a loop statement we can display total string.
putchar (name[i]);
printf (“%d”,x);
The above statement will display integer value 97 on the screen even though x is a character
variable, because when a character variable or character constant is used in an expression, it
is automatically converted in to integer value by the system. The integer value is equivalent
to ASCII code.
We can perform arithmetic operations on character constants and variables.
Ex: int x;
x=‟z‟-1;
printf(“%d”,x);
The above statement is valid statement and that will display 121 one as result, because ASCII
value of „z‟ is 122 and therefore the resultant value is 122 – 1 = 121.
atoi ( ) function:
This library function converts a string of digits into their integer values.
Functions Description
strlen ( )
strcpy ( )
strcmp ( )
strncmp ( )
Compares characters of two strings upto the specified length. Ignores case.
strnicmp ( )
strlwr ( )
strupr ( )
Duplicates a string
strdup ( )
strchr ( )
strrchr ( )
strstr ( )
strcat ( )
strncat ( )
strrev ( )
strset ( )
strspn ( )
Searches the first occurrence of the character in a given string and then it
strpbrk ( ) display the string from that character.
strlen ( ) function: This function counts the number of characters in a given string.
void main( )
{ (OR )
char a[80];
int len; void main()
clrscr( ); {
printf(“enter string:”); int s;
getch( ); }
}
Output: Output:
Total no of char‟s = 5
strcpy ( ) function: This function copies the content of one string to another. Here string1 is
source string and string2 destination string. String1 and string2 are character arrays. String1 is
copied into string2.
void main( )
clrscr( );
strcpy(s2,s1);
getch( );
Output:-
strncpy ( ) function: This function performs the same task as strcpy ( ). The difference between
them is that the strcpy( ) function copies the whole string to destination string. Whereas strncpy(
) function copies specified length of characters from source to destination string.
void main()
int n;
clrscr( );
gets(s1);
gets(s2);
strncpy(s2,s1,n);
getch( );
Output:
Destination string=wonderful
strcmp ( ) function: This function is used to compare two strings identified by the arguments and
it returns a value „0‟ if they are equal. If they are not equal it will return numeric difference
(ASCII) between the first non-matching characters.
void main( )
int s;
clrscr( );
s=strcmp(m1, m2);
printf(“ %d ”, s);
getch( );
Output:-
-1
Example Program2: To compare any strings using strcmp( ).
void main( )
int m;
clrscr( );
m = strcmp(s1, s2);
if(m==0)
else if(m<0)
getch( );
Output:-
enter 2 strings
mrcet
computers
mrcet computers
stricmp ( ) function: This function is used to compare two strings. The characters of the strings
may be in lower to upper case. This function does not determinate between the cases.
This function returns zero when two strings are same and it returns non-zero value if they are not
equal
{ s=stricmp(sr,tr);
clrscr( ); else
gets(sr); getche( );
strncmp ( ) function: This function is used to compare two strings. This function is same as
strcmp( ) but it compares the character of the string to a specified length
{
char sr[30], tr[30];
int s,n;
clrscr( );
printf (“\nEnter Source String:”);
gets(sr);
printf (“\nEnter Target String:”);
gets(tr);
printf(“\n Enter length up to which comparison is to be made:”); scanf(“%d”,&n);
s=strncmp(sr,tr,n);
if(s==0)
puts(“The two strings are Identical up to %d characters.”,n); else
puts(“The two strings are Different”);
getche( );}
Output:-
Enter Source String: goodmorning
Enter Target String: goODNIGHT
{
char sr[30], tr[30];
int s,n;
clrscr( );
s=strnicmp(sr,tr,n);
if(s==0)
puts(“The two strings are Identical up to %d characters.”,n);
else
Output:-
Enter Source String: goodmorning
Enter Target String: GOODNIGHT
Enter length upto which comparison is to be made5 The two strings are different.Enter Source
String: goodmorning
Enter length upto which comparison is to be made4 The two strings are identical up to 4
characters.strlwr ( ) function: This function can be used to convert any string to a lower case.
When you are passing any uppercase string to this function it converts into lower case.
Syntax: strlwr(string);
strupr ( ) function: This function is the same as strlwr( ) but the difference is that strupr( )
converts lower case strings to upper case.
Syntax: strupr(string);
strlwr(a);
strupr(b);
printf (“\n\n %s \t %s ”,a,b);
getch( );
}
Output:-
SACHIN Karan
sachin KARAN
strdup( ) function: This function is used for duplicating a given string at the allocated memory
which is pointed by a pointer variable.
clrscr( );
printf(“Enter text:”);
gets(s1);
s2 = strdup(s1);
printf(“\n original string = %s \n duplicate string = %s”,s1,s2);
getch();
}
Output:
Enter text: Engineering
original string = Engineering
duplicate string = Engineering
strchr( ) function: This function returns the pointer to a position in the first occurrence of the
character in the given string.
Where, string is character array, ch is character variable & chp is a pointer which collects
address returned by strchr( ) function.
gets(s);
printf(“\n Character to find:”);
ch = getchar( );
chp = strchr(string,ch);
if(chp)
getch( );}
Output:
Enter text: Hello how are you
Character to find: r
Character r found in string.
strrchr( ) function: In place of strchr( ) one can use strrchr( ). The difference between them is
that the strchr( ) searches occurrence of character from the beginning of the string where as
strrchr( ) searches occurrence of character from the end (reverse).
strstr( ) function: This function finds second string in the first string. It returns the pointer
location from where the second string starts in the first string. In case the first occurrence in the
string is not observed, the function returns a NULL character.
Syntax: strstr(string1,string2);
Example Program: To implement strstr( ) function for occurrence of second string in the
first string.
void main( )
{
char s1[30], s2[30], *chp;
clrscr( );
printf(“Enter text:”);
gets(s1);
printf(“\nEnter text:”);
gets(s2);
chp = strstr(s1,s2);
if(chp)
printf(“\n „%s‟ string is present in given string.”,s2);
else
Output:
Enter text: INDIA IS MY COUNTRY
Enter text: INDIA
„INDIA‟ string is present in given string.
strcat ( ) function: This function appends the target string to the source string. Concatenation of
two strings can be done using this function.
void main ( )
{
char s[80]=”Hello”,a[80] = “Mrcet”;
clrscr( );
printf(“\n %s \t %s”, s,a);
strcat(s,a); // strcat (s, “mrcet”);
Output:-
Hello Mrecw
HelloMrecw
strncat( ) function: This function is the same as that of strcat( ) function. The difference
between them is that the former does the concatenation of two strings with another up to the
specified length. Here, n is the number of characters to append.
Example Program: To append 2nd string with specified no. of characters at the end of the
string using strncat( ) function.
#include<string.h>
void main ( )
{
char s[80]="Hello",a[80] = "Mrcet";
int n;
clrscr( );
printf("\n s=%s \t a=%s", s,a);
strcat(s," ");
strncat(s,a,n);
printf ("\n %s ",s);
getch( );
}
Output:-
s= Hello a = Mrecw
Syntax: strrev(string);
{
char s[30]=”hello”;
clrscr( );
}
Output:- s1=hello
s2=olleh
{
char t[30];
clrscr( );
printf(“enter string:”);
scanf(“%s”, &t); // gets(t);
Output:
enter string: abcdefgh
strset( ) function: This function replaces every character of a string with the symbol given by
the programmer i.e. the elements of the strings are replaced with the arguments given by the
programmer.
Syntax: strset(string,symbol);
void main( )
clrscr( );
puts(“Enter string:”);
gets(st);
scanf(“%c”,&symbol);
strset(st,symbol);
getch( );
Output:
strnset( ) function: This function is the same as that of strset( ). Here the specified length is
provided. Where, n is the no. of characters to be replaced.
Syntax: strnset(string,symbol,n);
void main( )
int n;
clrscr( );
puts(“Enter string:”);
gets(st);
scanf(“%c”,&symbol);
strnset(st,symbol,n);
getch( );
Output:
strspn( ): This function returns the position of the string from where the source array does not
match with the target one.
Syntax: strspn(string1,string2);
Example Program: To indicate after what character the lengths of the 2 strings have no
match.
void main( )
int len;
clrscr( );
printf(“Enter string1:”);
gets(s1);
printf(“\nEnter string2:”);
gets(s2);
len = strspn(s1,s2);
getch( );
Output:
strpbrk( ) function: This function searches the first occurrence of the character in a given string
and then it display the string starting from that character.
Example Program: To print given string from first occurrence of given character.
void main( )
char *ptr;
clrscr( );
printf(“Enter string:”);
gets(string1);
gets(string2);
ptr = strpbrk(string1,string2);
printf(ptr);
getch();
Output:
Enter a character: d