0% found this document useful (0 votes)
135 views

Unit - Iii: Malla Reddy Engineering College For Women

This document discusses pointers in C programming. It defines pointers as variables that store memory addresses and can be used to indirectly access other variables in memory. It describes various pointer operations like dereferencing with *, pointer arithmetic, passing pointers to functions, and using pointers with arrays. Pointers allow inter-function communication, pass by reference, and accessing arrays more efficiently. The document provides examples of defining, declaring, and using pointers for various tasks in C.

Uploaded by

Hemanth Nani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
135 views

Unit - Iii: Malla Reddy Engineering College For Women

This document discusses pointers in C programming. It defines pointers as variables that store memory addresses and can be used to indirectly access other variables in memory. It describes various pointer operations like dereferencing with *, pointer arithmetic, passing pointers to functions, and using pointers with arrays. Pointers allow inter-function communication, pass by reference, and accessing arrays more efficiently. The document provides examples of defining, declaring, and using pointers for various tasks in C.

Uploaded by

Hemanth Nani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

COMPUTER PROGRAMMING UNIT-III

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.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 1


COMPUTER PROGRAMMING UNIT-III

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;

Eg:- int *ad; /* pointer to int */


char *s; /* pointer to char */
float *fp; /* pointer to float */
char **s; /* pointer to variable that is a pointer to char */

A pointer is a variable that contains an address which is a location of another variable


in memory.

Consider the Statement


p=&i;

Here ‘&’ is called address of a variable. ‘p’


contains the address of a variable i

The operator & returns the memory address of variable on which it is operated, this is
called Referencing.

The * operator is called an indirection operator or dereferencing operator which is


used to display the contents of the Pointer Variable.

Consider the following Statements :

int *p,x; x
=5; p= &x;
Assume that x is stored at the memory address 2000. Then the output for the

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 2


COMPUTER PROGRAMMING UNIT-III

following printf statements is :

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

POINTER FUNCTION ARGUMENTS

Function arguments in C are strictly pass-by-value. However, we can simulate pass-


by-reference by passing a pointer. This is very useful when you need to Support in/out(bi-
directional) parameters (e.g. swap, find replace) Return multiple outputs (one return value
isn't enough) Pass around large objects (arrays and structures).
/* Example of swapping a function can't change parameters */
void bad_swap(int x, int y)
{
int temp;
temp = x; x =
y;
y = temp;
}
/* Example of swapping - a function can't change parameters, but if a parameter is a pointer it
can change the value it points to */

void good_swap(int *px, int *py)


{
int temp;
temp = *px;
*px = *py; *py
= temp;
}

#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);
}

POINTERS AND ARRAYS :

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.

Consider the array

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 3


COMPUTER PROGRAMMING UNIT-III

2000 2002 2004 2006 2008

a[0] a[1] a[2] a[3] a[4]


The name of the array is called its base address.

i.e., a and k& a[20] are equal.

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

Reading and Printing an array using Pointers :


main()
{
int *a,i;
printf(“Enter five elements:”); for
(i=0;i<5;i++)
scanf(“%d”,a+i);
printf(“The array elements are:”); for
(i=o;i<5;i++)
printf(“%d”, *(a+i));
}

In one dimensional array, a[i] element is referred by (a+i) is


the address of ith element.
* (a+i) is the value at the ith element.

In two-dimensional array, a[i][j] element is represented as


*(*(a+i)+j)

POINTERS AND FUNCTIONS :

Parameter passing mechanism in ‘C’ is of two types.

1.Call by Value 2.Call


by Reference.

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.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 4


COMPUTER PROGRAMMING UNIT-III

Example of Call by Value:


#include <stdio.h>
void swap(int,int);
main()
{
int a,b;
printf(“Enter the Values of a and b:”);
scanf(“%d%d”,&a,&b); printf(“Before
Swapping \n”); printf(“a = %d \t b = %d”,
a,b); swap(a,b);
printf(“After Swapping \n”);
printf(“a = %d \t b = %d”, a,b);
}

void swap(int a, int b)


{
int temp;
temp = a; a =
b;
b = temp;
}

Example of Call by Reference:

#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 :

Incrementing/Decrementing a pointer variable ,adding and subtracting an integer from


pointer variable are all legal and known as pointer arithmetic. Pointers are valid operands in
arithmetic expressions ,assignment expressions ,and comparison expressions.
However not all the operators normally used in these expressions are valid in conjunction
with pointer variable.
A limited set of arithmetic operations may be performed on pointers. A pointer may
be incremented(+ +) or decremented(--) ,an integer may be added to a pointer
(+ or +=),an integer may be subtracted from a pointer(- or -=),or one pointer may be
subtracted from another.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 5


COMPUTER PROGRAMMING UNIT-III

We can add and subtract integers to/from pointers – the result is a pointer to another element
of this type

Ex : int *pa; char *s;

s-1 →points to char before s (1 subtracted)


pa+1→ points to next int (4 added!)
s+9 →points to 9th char after s (9 added)
++pa→ increments pa to point to next int

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.

NULL ptr is not the same as an EMPTY string.

const char* psz1 = 0;


const char* psz2 = "";
assert(psz1 != psz2);

Always check for NULL before dereferencing a pointer.

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);
}

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 6


COMPUTER PROGRAMMING UNIT-III

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

397870 234560 287650

pointer to pointer to integer pointer to integer integer variable


//statements
a=58;
p=&a;
q=&p;
printf(“%3d”,a);
printf(“%3d”,*p);
printf(“%3d”,**q);

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

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 7


COMPUTER PROGRAMMING UNIT-III

DYNAMIC MEMORY ALLOCATION :

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.

MEMORY ALLOCATION FUNCTIONS:

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.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 8


COMPUTER PROGRAMMING UNIT-III

CONTIGIOUS MEMORY ALLOCATION(calloc) :


Calloc is primarily used to allocate memory for arrys.It differs from malloc only in
that it sets memory to null characters. The calloc function declaration:
Void *calloc(size_t element_count, size_t element_size);

The result is the same for both malloc and calloc.


calloc returns the address of the first byte in the memory space allocated. If it is not
successful calloc returns null pointer.
Example:
If(!(ptr=(int*)calloc(200,sizeof
(int)))) //no memory
available
exit(100);
//memory available

In this example we allocate memory for an array of 200 integers.

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.

Void *realloc(void*ptr,size_t newsize);

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

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 9


COMPUTER PROGRAMMING UNIT-III

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.

Void free(void *ptr);

ptr ptr

Before After
Free(ptr);

In above example it releases a single element to allocated with a malloc,back to heap.

BEFORE AFTER

… …

Ptr 200 integers ptr 200 integers

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.

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 10


COMPUTER PROGRAMMING UNIT-III

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:

1. Reading and writing strings.


2. Combining strings together.
3. Coping one string to another.
4. Extracting a portion of a string.
5. Comparing string for equality.

Declaration and Initialization:

Every string is always declared as character array.

Syntax: char string_name [size];

Ex: char name[20];

We can initialize string as follows:

1. Char name[ ]={„H‟,‟E‟,‟L‟,‟L‟,‟O‟,‟\0‟};

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.

Memory map for above example:

H E L L O \0

2000 2001 2002 2003 2004 2005

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 11


COMPUTER PROGRAMMING UNIT-III

2. Char name [ ] = ”HELLO”.

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.

READING STRINGS FROM TERMINAL:


1. Using scanf ( ) function
To read strings from terminal we can use scanf ( ) function with „%s‟ format specifier.
Ex: char name [20];

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.)

2. By using gets ( ) function


By using gets ( ) function we can read a text which consists of more than one word which i
not possible with scanf ( ) function. This function is available in <stdio.h> header file.
Ex: gets (string);

Here string is a character array.

Ex: gets (“GOOD MORNING”):

We can pass string in double quotes as an argument.


MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 12
COMPUTER PROGRAMMING UNIT-III

3. By using getchar ( ) function

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.

Ex: char ch[20];


int i=0;
while ((ch[i]=getchar ( ) )!= „\n\)
{

i = i+1;
}

WRITING STRINGS TO SCREEN

1. BY USING PRINTF ( ) FUNCTION

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.

2. By using puts ( ) and putchar ( ) functions

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.

Ex: puts (“GOOD MORNING”);

We can use this function to display messages as shown above.

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.

Ex: char name [20];


for (i=0;i<5;i++)

putchar (name[i]);

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 13


COMPUTER PROGRAMMING UNIT-III

ARITHMETIC OPERATIONS ON CHARACTERS


Observe the following example:
char x = „a‟;

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.

Syntax: atoi ( string);


Ex: int x;
char no[5] = “2012”;
x = atoi(no);
printf(“%d”,x);
The above statement will display x value as 2012 (which is an integer).

String standard functions


The following table provides frequently used string handling functions which are supported
by C compiler.

Functions Description

Determines Length of a string

strlen ( )

Copies a string from source to destination

strcpy ( )

strncpy ( ) Copies specified number of characters of a string to another string

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 14


COMPUTER PROGRAMMING UNIT-III

Compares two strings (Discriminates between small and capital letters)

strcmp ( )

Compares two strings (Doesn‟t Discriminates between small and capital


stricmp ( ) letters)

Compares characters of two strings upto the specified length

strncmp ( )

Compares characters of two strings upto the specified length. Ignores case.

strnicmp ( )

Converts upper case characters of a string to lower case

strlwr ( )

Converts lower case characters of a string to upper case

strupr ( )

Duplicates a string

strdup ( )

Determines first occurrence of a given character in a string

strchr ( )

Determines last occurrence of a given character in a string

strrchr ( )

Determines first occurrence of a given string in another string

strstr ( )

Appends source string to destination string

strcat ( )

Appends source string to destination string upto specified length

strncat ( )

Reverses all characters of a string

strrev ( )

Sets all characters of string with a given argument or symbol

strset ( )

Sets specified number of characters of string with a given argument or


strnset ( ) symbol

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 15


COMPUTER PROGRAMMING UNIT-III

Finds up to what length two strings are identical

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.

Syntax: strlen(string); (or) strlen(“ string”);

Example Program: To implement the purpose of strlen():

void main( )

{ (OR )
char a[80];
int len; void main()
clrscr( ); {
printf(“enter string:”); int s;

scanf(“%s”,a); // (or) get (a); clrscr( );


len=strlen(a); s=strlen(“MRCET”);
printf(“\n Name = %s”, a);
printf(“\nTotal no of char‟s =%d”, s);
printf(“\n Total no of char‟s = %d”, len); getch( );

getch( ); }
}

Output: Output:

Enter string: MRCET


Name = MRCET
Total no of char‟s = 5

Total no of char‟s = 5

MALLA REDDY ENGINEERING COLLEGE FOR WOMEN Page 16


COMPUTER PROGRAMMING UNIT-III

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.

Syntax: strcpy(string2, string1); or strcpy(destination, source);

Example Program: To implement the purpose string copy( ).

void main( )

char s1[80]=”sachin”, s2[80];

clrscr( );

printf (“\n\n \t given string =%s”, s1);

strcpy(s2,s1);

printf(“\n\n \t copied string = %s ”, s2);

getch( );

Output:-

given string =sachin

copied string =sachin

MALLA REDDY ENGINEERING COLLEGE Page 17


COMPUTER PROGRAMMING UNIT-III

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.

Syntax: strncpy(string2, string1,n); or strcpy(destination, source,n);


Example Program: To copy source string to destination string up to a specified length.

Length is to be entered through the keyboard.

void main()

char s1[15], s2[15];

int n;

clrscr( );

printf (“\nEnter Source String:”);

gets(s1);

printf (“\nEnter Destination String:”);

gets(s2);

printf(“\n Enter no. of characters to replace in Destination string:”); scanf(“%d”,&n);

strncpy(s2,s1,n);

printf(“\n Source string = %s ”, s1);

printf(“\n Destination string = %s ”, s2);

getch( );

Output:

Enter Source String: wonderful

Enter Destination String: beautiful

MALLA REDDY ENGINEERING COLLEGE Page 18


COMPUTER PROGRAMMING UNIT-III

Enter no. of characters to replace in Destination string: 6

Source string = wonderful

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.

Syntax: strcmp(string1, string2);

Example Program1: To compare any strings using strcmp( ).

void main( )

char m1[30]=”amar”, m2[30] = “balu”;

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;

MALLA REDDY ENGINEERING COLLEGE Page 19


COMPUTER PROGRAMMING UNIT-III

char s1[30], s2[30];

clrscr( );

printf(“enter 2 string \n”);

scanf(“%s%s”, &s1, &S2);

printf(“\n\n\n\t %s \t %s”, s1, s2);

m = strcmp(s1, s2);

printf(“\n\n \t %d”, m);

if(m==0)

printf(“\n\n both the strings are equal”);

else if(m<0)

printf(“\n\n first string is less than second string \n”);


else

printf(“\n\n first string is greater than second string \n”);

getch( );

Output:-

enter 2 strings

mrcet

computers

MALLA REDDY ENGINEERING COLLEGE Page 20


COMPUTER PROGRAMMING UNIT-III

mrcet computers

First string is greater than second string

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

Syntax: stricmp(string1, string2);

Example Program: To compare two strings using stricmp( ).

void main( ) gets(tr);

{ s=stricmp(sr,tr);

char sr[30], tr[30]; if(s==0)

int s; puts(“The two strings are Identical.”);

clrscr( ); else

printf (“\nEnter Source String:”); puts(“The two strings are Different”);

gets(sr); getche( );

printf (“\nEnter Target String:”); }


Output:-

Enter Source String: HELLO

Enter Target String: hello

The two strings are Identical.

MALLA REDDY ENGINEERING COLLEGE Page 21


COMPUTER PROGRAMMING UNIT-III

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

Syntax: strncmp(string1, string2,n); or strncmp(source, target, arguments);

Example Program: To compare two strings using strncmp( ).


void main( )

{
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

Enter length up to which comparison is to be made:2


The two strings are Identical up to 2 characters.
strnicmp ( ) 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.

Syntax:strnicmp(string1, string2,n); (or) strnicmp(source, target, arguments);


Example Program: To compare two strings using strnicmp( ).
void main( )

MALLA REDDY ENGINEERING COLLEGE Page 22


COMPUTER PROGRAMMING UNIT-III

{
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=strnicmp(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
Enter length upto which comparison is to be made5 The two strings are different.Enter Source
String: goodmorning

Enter Target String: GOODNIGHT

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.

MALLA REDDY ENGINEERING COLLEGE Page 23


COMPUTER PROGRAMMING UNIT-III

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);

Example Program: To implment the purpose of string upper()& string lower().


void main ( )
{
char a[80]=”SACHIN”, b[80] = “Karan”;
clrscr( );
printf(“\n\n %s \t %s”, a,b);

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.

Syntax: string2 = strdup(string1);


Example Program: To enter the string and get it‟s duplicate.
void main( ){

MALLA REDDY ENGINEERING COLLEGE Page 24


COMPUTER PROGRAMMING UNIT-III

char s1[10], *s2;

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.

Example Program: To find first occurrence of a given character in a given string.


void main( )
{
char s[30], ch, *chp;
clrscr( );
printf(“Enter text:”);

gets(s);
printf(“\n Character to find:”);
ch = getchar( );
chp = strchr(string,ch);
if(chp)

MALLA REDDY ENGINEERING COLLEGE Page 25


COMPUTER PROGRAMMING UNIT-III

printf(“\n character %c found in string.”,ch);


else
printf(“\n character %c not found in string.”,ch);

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).

Syntax: chp = strrchr(string, ch);

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);

MALLA REDDY ENGINEERING COLLEGE Page 26


COMPUTER PROGRAMMING UNIT-III

chp = strstr(s1,s2);
if(chp)
printf(“\n „%s‟ string is present in given string.”,s2);
else

printf(“\n „%s‟ string is not present in given string.”,s2);


getch( );}

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.

Syntax: strcat(string1, string2);

Example Program: To implement the purpose of string concat().


#include<string.h>

void main ( )
{
char s[80]=”Hello”,a[80] = “Mrcet”;
clrscr( );
printf(“\n %s \t %s”, s,a);
strcat(s,a); // strcat (s, “mrcet”);

printf (“\n %s ”,s);


getch( );
}

MALLA REDDY ENGINEERING COLLEGE Page 27


COMPUTER PROGRAMMING UNIT-III

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.

Syntax: strncat(string1, string2, n);

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);

printf("\n Enter no. of characters to add:");


scanf("%d",&n);

strcat(s," ");
strncat(s,a,n);
printf ("\n %s ",s);
getch( );
}

MALLA REDDY ENGINEERING COLLEGE Page 28


COMPUTER PROGRAMMING UNIT-III

Output:-

s= Hello a = Mrecw

Enter no. of characters to add: 2


Hello Mr
Strrev ( ) function: This function simply reverses the given string.

Syntax: strrev(string);

Example Program1: To implement the purpose of string reverse().


#include<string.h>

{
char s[30]=”hello”;
clrscr( );

printf("\n\n original text = %s",s);


strrev(s);
printf ("\n\n reverse of text = %s",s);
getch( );

}
Output:- s1=hello
s2=olleh

Example Program2: To implement the purpose of string reverse().


void main( )

{
char t[30];

MALLA REDDY ENGINEERING COLLEGE Page 29


COMPUTER PROGRAMMING UNIT-III

clrscr( );
printf(“enter string:”);
scanf(“%s”, &t); // gets(t);

printf(“\n\n given string = %s”,t);


strrev(t);
printf (“\n\n reversed string = %s”,t);
getch( );
}

Output:
enter string: abcdefgh

given string = abcdefgh


reversed string = hgfedcba

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( )

char st[15], symbol;

clrscr( );

puts(“Enter string:”);

MALLA REDDY ENGINEERING COLLEGE Page 30


COMPUTER PROGRAMMING UNIT-III

gets(st);

puts(“Enter symbol for replacement:”);

scanf(“%c”,&symbol);

printf(“\n\n Before strset( ): %s”,st);

strset(st,symbol);

printf(“\n After strset( ): %s”,st);

getch( );

Output:

Enter string: LEARN C

Enter symbol for replacement: Y

Before strset( ): LEARN C

After strset( ): YYYYYY

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( )

MALLA REDDY ENGINEERING COLLEGE Page 31


COMPUTER PROGRAMMING UNIT-III

char st[15], symbol;

int n;

clrscr( );

puts(“Enter string:”);

gets(st);

puts(“\nEnter symbol for replacement:”);

scanf(“%c”,&symbol);

puts(“\nHow many string characters to be replaced:”);


scanf(“%d”,&n);

printf(“\n\n Before strset( ): %s”,st);

strnset(st,symbol,n);

printf(“\n After strset( ): %s”,st);

getch( );

Output:

Enter string: ABCDEFGHIJ

Enter symbol for replacement: +

MALLA REDDY ENGINEERING COLLEGE Page 32


COMPUTER PROGRAMMING UNIT-III

How many string characters to be replaced: 5

Before strset( ): ABCDEFGHIJ

After strset( ): +++++FGHIJ

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( )

char s1[10], s2[10];

int len;

clrscr( );

printf(“Enter string1:”);

gets(s1);

printf(“\nEnter string2:”);

gets(s2);

len = strspn(s1,s2);

printf(“\n\n After %d characters there is no match.\n”, len);


MALLA REDDY ENGINEERING COLLEGE Page 33
COMPUTER PROGRAMMING UNIT-III

getch( );

Output:

Enter string1: GOOD MORNING

Enter string2: GOOD BYE

After 5 characters there is no match.

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.

Syntax: strpbrk(string1, string2);

Example Program: To print given string from first occurrence of given character.

void main( )

char string1[20], string2[10];

char *ptr;

clrscr( );

printf(“Enter string:”);

MALLA REDDY ENGINEERING COLLEGE Page 34


COMPUTER PROGRAMMING UNIT-III

gets(string1);

printf(“\n Enter a character:”);

gets(string2);

ptr = strpbrk(string1,string2);

puts(“\n String from given character:”);

printf(ptr);

getch();

Output:

Enter string1: Good morning

Enter a character: d

String from given character: d morning.

MALLA REDDY ENGINEERING COLLEGE Page 35

You might also like