Pointers and Strings
Pointers and Strings
Pointers – Introduction (Basic Concepts), Pointers for inter function communication (call by
value and call by reference), pointers to pointers, compatibility, void pointer, null pointer,
dangling pointer, passing an array to a function, Pointer Applications - Arrays and Pointers,
Pointer Arithmetic , Pointer to functions.
Dynamic Memory allocation –Memory allocation functions -malloc(), calloc(), realloc(), free(),
Allocating memory for arrays of different data types,. C program examples.
Strings – Concepts, C Strings, String Input / Output functions, arrays of strings, string
manipulation functions, C program examples.
MITS Page 1
CPDS UNIT -III
POINTERS
INTRODUCTION
A pointer is a variable that stores a memory address of another variable. Pointers are one of the
derived types in C.
POINTER CONCEPTS
The basic data types in C are int, float, char double and void. Pointer is a special data
type which is derived from these basic data types.
Pointer Constants
Pointer Values
Pointer Variables
POINTER CONSTANTS
As we know, computers use their memory for storing the instructions of a program, as
well as the values of the variables that are associated with it.
The computer’s memory is a sequential collection of ‘storage cells’.
Each cell can hold one byte of information, has a unique number associated with it called
as ‘address’.
The computer addresses are numbered consecutively, starting from zero. The last address
depends on the memory size.
Let us assume the size of the memory is 64K then,
MITS Page 2
CPDS UNIT -III
Even bank is set of memory locations with even addresses. Like 0, 2, 4, 6……65534.
Odd bank is set of memory locations with odd addresses. Like 1, 3, 5 ….65535.
0 1
2 3
4 5
.. ..
.. ..
32278 32279
.. ..
65530 65531
65532
65534 65535
POINTER VALUE
Whenever we declare a variable, the system allocates , an appropriate location to hold the
value of the variable somewhere in the memory,.
MITS Page 3
CPDS UNIT -III
int i = 10;
We can represent i’s location in the memory by the following memory map:
i Variable Name
Variable value
10
65510 Variable address
Pointer Values
The address of the variable cannot be accessed directly. The address can be obtained by
using address operator(&) in C language.
The address operator can be used with any variable that can be placed on the left side of
an assignment operator.
The format specifier of address is %u(unsigned integer),the reason is addresses are
always positive values. We can also use %x to know the address of a variable.
Example, to know the address of variable n, just use &n.
Note: Constants, expressions, and array name cannot be placed on the left side of the assignment
and hence accessing address is invalid for constants, array names and expressions.
POINTER VARIABLE
MITS Page 4
CPDS UNIT -III
A variable Which holds the address of some other variable is called pointer variable.
A pointer variable should contain always the address only.
The * Operator
For accessing the variables through pointers, the following sequence of operations have to be
performed, to use pointers.
In C , every variable must be declared before they are used. Since the pointer variables
contain address that belongs to a another variable, they must be declared as pointers before we
use them.
This tells the compiler three things about the variable ptr_name.
For example,
int *p;
declares the variable p as a pointer variable that points to an integer data type. Remember that
the type int refers to the data type of the variable being pointed by p.
Initializing Pointers
MITS Page 5
CPDS UNIT -III
Once a pointer variable has been declared, it can be made to point to a variable using
statement such as
ptr_name = &var;
Which cause ptr_name to point to var.Now ptr_name contains the address of var. This is
known as pointer initialization.
Before a pointer is initialized it should not be used.
Once a pointer variable has been assigned the address of a variable, we can access the
value of a variable using the pointer. This is done by using the indirection operator(*).
*ptr_name
Example1
MITS Page 6
CPDS UNIT -III
The above program illustrates how to access the variable using pointers. After finding the
first statement i = 10, the compiler creates a variable i with a value of 10 at a memory location.
Then coming to line 2 and 3 a pointer variable pi is create and initialized with the address of the i
variable. then the compiler automatically provides a link between these two variables as follows.
i pi
10 8342
8342 8338
Example2
The following code illustrates how to declare int ,char and float pointers. Here we have
declared three variables of type int, float and char ,also three pointer variables points to int, float
and char. Remember here pf points to the value of type float but its type is unsigned integer
only.
MITS Page 7
CPDS UNIT -III
MITS Page 8
CPDS UNIT -III
int * pa;
int * pb;
Example:
Sum = *pa + *pb;
Dangling Pointers
A pointer variable should contain a valid address. A pointer variable which does not
contain a valid address is called dangling pointer.
For example, consider the following declaration,
int *pi;
This declaration indicates that pi is a pointer variable and the corresponding memory
location should contain address of an integer variable.
But , the declaration will not initialize the memory location and memory contains garbage
value.
CPDS UNIT -III
Note: We cannot use a pointer variable to the register variable. The reason is that, user does not
know the address of the register variable. So we are not able to use pointer variable on register
variables.
POINTER ARITHMETIC
Example:
int i=4 ,pi=&i; //(assume address of i=1000)
float j,*pj=&j;// (assume address of j=2000)
pi = pi + 1; // here pi incremented by (1*data type times)
pi = pi + 9; // pi = 1000 + (9*2) 1018 address
pj = pj + 3; // pj=1018+(3*4)1030 address
Example:
int i=4,*pi=&i; //assume address of i =1000)
char c, *pc=&c; // assume address of c = 2000
double d, *pd=&d; // assume address of d=3000
pi = pi-2; /* pi=1000-(2*2)=996 address */
pc = pc-5; /* pc=2000-(5*1)=1985 address
pd = pd-6; /* pd=3000-(6*8)=2952 address */
Pointer variables may be subtracted from one another. This is helpful while finding
array boundaries. Be careful while performing subtraction of two pointers.
Pointer variables can be used in comparisons, but usually only in a comparison to NULL.
We can also use increment/decrement operators with pointers this is performed same as
adding/subtraction of integer to/from pointer.
MITS Page 10
CPDS UNIT -III
POINTER EXPRESSIONS
Like other variables, pointer variables can be used in expressions. For example, if p1 and
p2 are two valid pointers ,then the following statements are valid.
a= *p1 + *p2;
sum = sum + *p1;
z = 10 / *p2;
f = *p1 * i;
Note: be careful while writing pointer expressions .The expression *p++ will result in the
increment of the address of p by data type times and points to the new value. Whereas the
expression (*p) ++ will increments the vale at the address. If you are not properly coded you will
get some unwanted result.
NULL Pointer
If wish to have a pointer that points to “nowhere”, should make this explicit by assigning
it to NULL.
If it is too early in the code to assign a value to a pointer, then it is better to assign NULL
(i.e., \0 or 0).
The integer constants 0 and 0L are valid alternatives to NULL, but the symbolic constant
is (arguably) more readable.
A NULL pointer is defined as a special pointer.
It can be used along with memory management functions.
POINTERS TO POINTERS
It is possible to make a pointer to point to another pointer variable. But the pointer must
be of a type that allows it to point to a pointer.
A variable which contains the address of a pointer variable is known as pointer to pointer.
Its major application is in referring the elements of the two dimensional array.
Syntax for declaring pointer to pointer,
ptr_ptr=&ptr_name;
MITS Page 11
CPDS UNIT -III
This initialization tells the compiler that now ptr_ptr points to the address of a pointer
variable.
Accessing the element value,
**ptr_ptr;
It is equalent to *(*(&ptr_name));
Example
The above program illustrates the use of pointers to pointers. Here, using two indirection
operators the data item 16 can be accessed (i.e., *ppi refers to pi and **ppi refers to i).
POINTER COMPATIBILITY
We should not store the address of a data variable of one type into a pointer variable of
another type.
During assigning we should see that the type of data variable and type of the pointer
variable should be same or compatible. Other wise it will result in unwanted output.
The following program segment is wrong,
int i=10;
MITS Page 12
CPDS UNIT -III
float *pf;
It is possible to use incompatible pointer types while assigning with type casting pointer.
Casting pointers :When assigning a memory address of a variable of one type to a pointer that
points to another type it is best to use the cast operator to indicate the cast is intentional (this will
remove the warning).
Example:
int V = 101;
float *P = (float *) &V; /* Casts int address to float * */
void Pointer
A pointer to void is a generic type that is not associated with a reference type.
It is neither the address of a character nor an integer, nor a float nor any other type.
It is compatible for assignment purposes only with all other pointer types.
A pointer of any reference type can be assigned to a pointer to void type.
A pointer to void type can be assigned to a pointer of any reference type.
Certain library functions return void * results.
No cast is needed to assign an address to a void * or from a void * to another pointer
type.
Where as a pointer to void can not be deferenced unless it is cast.
void *
void
Example 1:
int V = 101;
float f=98.45;
void *G = &V; /* No warning */
printf (“%d”,*((int*)G)); /* Now it will display 101
G = &f; /* No warning, still not safe */
printf (“%f”,*((float*)G)); /* Now it will display 98.45
MITS Page 13
CPDS UNIT -III
Example 2:
void main()
{
void *p;
int a=32;
float k=43.65;
clrscr();
p=&a;
printf("The value of a=%d",*(int *)p);
p=&k;
printf("\nThe value of k=%f",*(float *)p);
getch();
}
OUTPUT
MITS Page 14
CPDS UNIT -III
The array name a represents the base address of the array (i.e. 5000)
Example program:
#include<stdio.h>
int main()
{
int a[5] = { 1, 2, 3, 4, 5 };
int *p;
p = a;
printf("The base address of array:%u\n", a);
printf("The address stored in the pointer:%u\n", p);
return 0;
}
OUTPUT
Pointer to arrays
The pointer that points to whole array instead of only one element of the array is called
pointer to array.
Syntax:
data_type (*var_name)[size_of_array];
Example:
int (*p)[5];
Here p is pointer that can point to an array of 5 integers.Since subscript have higher
precedence than indirection, it is necessary to enclose the indirection operator and pointer name
inside parentheses. Here the type of p is ‘pointer to an array of 5 integers’.
Note : The pointer that points to the 0th element of array and the pointer that points to the whole
array are totally different. The following program shows this:
MITS Page 15
CPDS UNIT -III
output
p1 = 5000, p2 = 5000
p1 = 5002, p2 = 5010
p1: is pointer to 0th element of the array a, while p2 is a pointer that points to the whole array a.
The base type of p1 is int while base type of p2 is ‘an array of 5 integers’.
We know that the pointer arithmetic is performed relative to the base size, so if we write
p2++, then the pointer p2 will be shifted forward by 10 bytes.
MITS Page 16
CPDS UNIT -III
Program Memory
Data Memory
MITS Page 17
CPDS UNIT -III
Storage of C program
The program instructions and global and static variables are stored in the region known
as permanent storage area.
Local variables are stored in stack area.
The heap area is used for dynamic memory allocation ata run time.
The size of the heap keep changing when program is executed due to the creation and
death of variables.
Static Memory Allocation
Static memory allocation requires that the declaration and definition of memory be fully
specified in the source program. The number of bytes reserved cannot be changed during run
time. This is the technique we have used to this point to define variables, arrays, pointers, and
streams.
MITS Page 18
CPDS UNIT -III
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
data declaration, to run time.
They are
malloc()
calloc()
realloc()
free()
First three are used for memory allocation and fourth is used for return memory when it is no
longer needed. All the memory management functions are found in the standard library file
stdlib.h.
The malloc() function allocates a block of memory that contains the number of bytes
specified in its parameters. It returns a void pointer to the first byte of the allocated memory.
The allocated memory is not initialized.
Function prototype is
The type, size_t is defined in several header files including stdio.h. The type is usually an
unsigned integer.
MITS Page 19
CPDS UNIT -III
p = malloc(sizeof(int));
malloc function returns the address of the first byte in the memory space allocated. If it
is not successful, it return NULL pointer. An attempt to allocate memory from the heap when the
memory is insufficient is known as overflow. It is up to the program to check for memory
overflow. If it doesn’t the program produces the invalid results or aborts with an invalid address
the first time the pointer is used.
If we call malloc() with a zero size, the results are unpredictable. It may return NULL
pointer or it may return some other implementation dependent value.
Prior to C99, it was necessary to cast the pointer returned from a memory allocation
function. The casting format is
p = (type*) malloc(size);
Ex: p = (int*)malloc(4*sizeof(int));
The compiler allocates the space equal to 4 times of integer.and the address of first byte
is allocated to pInt.
5000
5000
8 bytes of space
MITS Page 20
CPDS UNIT -III
PROGRAM:
#include<alloc.h>
int main()
int *p,*q,x,n,i,j=0;
scanf("%d",&n);
p=(int *)malloc(n*sizeof(int));
q = p;
printf("Enter values:");
for(i=0;i<n;i++)
scanf("%d",&x);
*p = x;
p++;
for(i=0;i<n;i++)
printf("%4d",*q);
q++;
return 0;
MITS Page 21
CPDS UNIT -III
OUTPUT
Enter values:55 44 66 11 22
given values: 55 44 66 11
calloc () is primarily used to allocate memory for arrays. It differs from malloc only in that
it sets memory to null characters. The declaration is as follows
Syntax of calloc()
6000
0 0 0 0 0
Memory is allocated for array of 5 elements of float type. The address of 1st byte is
represented by the pointer variable p. The array locations are initialized with zeros.
It is highly efficient function. When given a memory 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 block. If the memory cannot be extended because of other allocations, realloc() allocates a
MITS Page 22
CPDS UNIT -III
completely new block, copies the existing memory allocation to the new allocation and deletes
the old allocation. The declaration is as follows
ptr = realloc(ptr, newsize);
Example
Ptr
Before
18 55 33 121 64 1 90 31 5 77
10 Integers
New
Ptr=realloc(ptr,15*sizeof(int)); elements not
ptr
18 55 33 121 64 1 90 31 5 77 ? ? ? ? ?
15 Integers
After
MITS Page 23
CPDS UNIT -III
Program
#include<stdio.h>
#include<stdlib.h>
int main()
int *p,i,j,n;
p =(int *)malloc(3*sizeof(int)) ;
for(i=0;i<3;i++)
scanf("%d",(p+i));
for(i=0;i<3;i++)
printf("\t%d",*(p+i));
p = realloc(p,5);
for(j=i;j<5;j++)
scanf("%d",(p+j));
for(i=0;i<5;i++)
printf("\t%d",*(p+i));
return 0;
Output
MITS Page 24
CPDS UNIT -III
When memory locations allocated by malloc, calloc or realloc are no longer needed, they
should be freed using 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 bloc, a pointer that is a different type
than the pointer that allocated the memory, it is also a potential error to refer to memory after
it has been released. The function declaration is
Example: free(ptr);
Releasing memory does no change the value in the pointer. It still contains the address in the
heap. It is logic error to use the pointer after memory has been released.
Note : The pointer used to free memory must be of the same type as the pointer used to
allocate memory.
MITS Page 25
CPDS UNIT -III
STRINGS
Declaring a String
Declaring Strings
MITS Page 26
CPDS UNIT -III
String extraction
String reverse
Character arrays may be initialized when they are declared. C permits a character array to be
initialized in one of the following forms,
Initializing Strings
Since a sting is stored in an array of characters, we do not need to indicate the size of the array if
we initialize.
Ex : char str[] = “C Program”;
In the above case, the compiler will create an array of 10 bytes and initializes it with “C
Program” and a null character. If we now tried to store “Programming” in str array it is not
possible as the length is not sufficient. So, a string variable is initialized with a longest value.
C provides two more ways to initialize strings. A common method is to assign a string literal to a
character pointer.
Ex : char *pStr = “Hello World”;
We can also initialize a string as an array of characters. This method is not used too often
because it is so tedious to code.
Ex: char str[12] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘\0’ }
If you know all the characters at compile time, you can specify all your data within brackets:
Example,
char s[6]={‘h’,’e’,’l’,’l’,’o’,’0’};
MITS Page 27
CPDS UNIT -III
The compiler allocates 6 memory locations ranging from 0 to 5 and these locations are initialized
with the characters in the order specified. The remaining locations are automatically initialized to
null characters as shown in the below figure .
h e l l o \0
1000 1001 1002 1003 1004 1005 Address
If the number of characters values to be initialized is less than the size of the array, then
the characters are initialized in the order from 0th location. The remaining locations will be
initialized to NULL automatically. Consider the following initialization,
char s[10]={‘h’,’e’,’l’,’l’,’o’};
The above statement allocates 10 bytes for the variable s ranging from 0 to 9 and initializes first
5 locations with the characters. The remaining locations are automatically filled with NULL as
shown in below figure 4.10.
s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]
h e l l o \0 \0 \0 \0 \0
200 201 202 203 204 205 206 207 208 209 --> Address
If we omit the size of the array, but specify an initial set of characters, the compiler will
automatically determine the size of the array. This way is referred as initialization without size.
char s[]={‘h’,’e’,’l’,’l’,’o’};
In this declaration, even though we have not specified exact number of characters to be used
in array s, the array size will be set of the total number of initial characters specified and appends
the NULL character.. Here, the compiler creates an array of 6 characters. The array s is
initialized as shown in Figure .
MITS Page 28
CPDS UNIT -III
h e l l o \0
1000 1001 1002 1003 1004 1005 Address
char s[]=”hello”;
Here the length of the string is 5 bytes, but size is 6 bytes. The compiler reserves 5+1 memory
locations and these locations are initialized with the characters in the order specified. The string
is terminated by Null as shown in the figure 4.12.
h e l l o \0
1000 1001 1002 1003 1004 1005 Address
MITS Page 29
CPDS UNIT -III
Ex : char *Str;
char str[6];
scanf(“%s”,str);
The above statements are used to read string from input and stored in the string variable str;
h e l l o \0
1000 1001 1002 1003 1004 1005 Address
printf(“%s”,str);
puts(str);
The above statements are used to display the string on the output
Character Input/Output
1.i) getchar()
The function reads character type from the standard input. It reads one character at a time till the
user presses the enter key.
ii) putchar()
This function prints one character on he screen at a time which is read by the standard input.
MITS Page 30
CPDS UNIT -III
Output
Enter a character : M
M
2.i) getc()
The function reads a character from the standard input or a file. It reads one character at a time
till the user presses the enter key.
ii) putc()
This function prints one character on the screen or to a file. At a time which is read by the
standard input.
void main()
{
char ch;
printf("Enter a character :");
ch = getc(stdin);
putc(ch,stdout);
}
Output
Enter a character : M
M
String Input/Output
In addition to the formatted string functions, C has two sets of string functions that read
and write strings without reformatting any data. These functions convert text-file lines to strings
and strings to text-file lines.
C provides two parallel set of functions, one for characters and one for wide characters.
They are virtually identical except for the type.
Line to String
The gets() and fgets() functions take a line from the input stream and make a null
terminated string out of it. They are therefore sometimes called line-to-string input functions.
The function declarations for get string are shown below
char* gets (char* strPtr);
char* fgets(char* strPtr, int size, FILE* sp);
The source of data for the gets is standard input; the source of data for fgets can be a file
or standard input. Both accept a string pointer and return the same pointer if the input is
successful.
MITS Page 31
CPDS UNIT -III
If any input problems occur, such as detecting end-of-file before reading any data, they
return NULL.
If no data were read the input area is unchanged.
If an error occurs after some data have been read, the contents of the read-in area cannot
be determined.
Since no size is specified in gets, it reads data until it finds a new line or until the end of file. If
new line character is read, it is discarded and replaced with a null character.
The fgets function requires two additional parameters: one specifying the array size that is
available to receive the data and other a stream. It can be used with the keyboard by specifying
the stdin. In addition to new-line and end of file, the reading with stop when size-1 characters
have been read.
/* Program to determine the usage of gets and fgets*/
#include<stdio.h>
void main()
{
char name[20], add[50];
printf(“Enter your name :”);
gets(name);
printf(“Enter your address :”);
fgets(add, sizeof(add), stdin);
printf(“ Name = %s\n Address = %s”, name,add);
}
Output
Enter your name : Sukruth
Enter your address : Hyderabad
Name = Sukruth
Address = Hyderabad
String to Line
The puts/fputs functions take a null-terminated string from memory and write it to a file
or the keyboard. All change the string to a line. The null character is replaced with a newline is
puts; it is dropped in fputs. Because puts is writing to the standard output unit, usually a display,
this is entirely logical. On the other hand, fputs is assumed to be writing to a file where newlines
are not necessarily required.
The declarations for these functions are
int puts( const char* strPtr);
int fputs( const char* strPtr, FILE* sp);
MITS Page 32
CPDS UNIT -III
gets(str);
puts(str);
fputs(str, stdout);
fputs(“\n”,stdout);
fputs(str+5, stdout);
}
Output
OUTPUT
MITS Page 33
CPDS UNIT -III
Explanation: Here length of the string is found by counting characters from first character to
null character(‘/0’)
Initially the variable i has 0;
i will be incremented by one every time
Loop will terminate when name[i] reaches to ‘\0’
2. Copy a string
/*Program to copy a string to another without using string functions */
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20], str2[20];
int i;
printf("Enter first string :");
scanf("%s",str1);
for(i = 0;str1[i]!='\0';i++)
{
str2[i] = str1[i];
}
str2[i] = ‘\0’;
printf("Given String = %s\n",str1);
printf("Copied String = %s",str2);
return 0;
}
OUTPUT
3. String reverse
/*Program to reverse a string without using string functions */
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20], str2[20];
int i=0,j=0,len=0;
printf("Enter a string :");
scanf("%s",str1);
while(str1[i++] !='\0')
MITS Page 34
CPDS UNIT -III
{
len++;
}
for(i=len-1,j=0; i>=0; i--,j++)
{
str2[j] = str1[i];
}
str2[j] = '\0';
printf("Reverse String = %s",str2);
return 0;
}
OUTPUT
In the above program string is reversed by copying the str1 from character to first character in
the str2 from beginning . Finally put ‘\0’ in the last position of str2
MITS Page 35
CPDS UNIT -III
MITS Page 36
CPDS UNIT -III
C has provided a rich set of string functions. These functions make program easier and
provides the opportunity to make them more efficient when the operation is supported by
hardware instructions.
The traditional string functions have a prefix of str. The basic format is
int str…. (parameters)
The string character functions are found in the string library (string.h).
String functions
String functions Description
strcat ( ) Concatenates str2 at the end of str1
strncat ( ) Appends a portion of string to another
strcpy ( ) Copies str2 into str1
strncpy ( ) Copies given number of characters of one string to another
strlen ( ) Gives the length of str1
Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1 >
strcmp ( )
str2
Same as strcmp() function. But, this function negotiates case. “A” and “a”
strcmpi ( )
are treated as same.
strchr ( ) Returns pointer to first occurrence of char in str1
strrchr ( ) last occurrence of given character in a string is found
strstr ( ) Returns pointer to first occurrence of str2 in str1
MITS Page 37
CPDS UNIT -III
String Length
The string length function strlen returns the length of a string specified as the number of
characters in the string excluding the null character. If the string is empty it returns zero. The
function declaration is as follows
int strlen(const char* string);
/* Program to find the length of string using strlen() function */
#include<string.h>
#include<stdio.h>
void main()
{
char ch[20];
int len=0;
printf("Enter a string :");
scanf("%s",ch);
len= strlen(ch);
printf("Length = %d",len);
getch();
}
Output
Enter a string : hai
Length = 3
String Copy
C has two copy functions. The first strcpy copies the contents of one string to another.
The second strncpy copies the contents of one string to another but it sets a maximum number of
characters that can be moved.
MITS Page 38
CPDS UNIT -III
char str1[20],str2[20];
printf("Enter a string :");
scanf("%s",str1);
strcpy(str2,str1);
printf("Copied String = %s",str2);
}
Output
Enter a string : C Program
Copied String = C Program
String Compare
C has two string compare functions. The first strcmp compares two string until unequal
characters are found or until the end of the strings reached. The second strncmp compares until
unequal characters are found, a specified number of characters have been tested or until the end
of a string is reached.
Both functions return an integer to indicate the results of the compare.
If the two stings are equal, the return value is zero.
If the first parameter is less than the second parameter, the return value is less than zero
i.e. negative value.
MITS Page 39
CPDS UNIT -III
If the first parameter is greater than the second parameter, the return value is greater than
zero i.e. positive value.
MITS Page 40
CPDS UNIT -III
clrscr();
printf("Enter first string :");
scanf("%s",str1);
printf("Enter second string :");
scanf("%s",str2);
i=strncmp(str1,str2,3);
if(i==0)
printf("Strings are Equal");
else
printf("Strings are not Equal");
}
Output
Enter first string : Good Morning
Enter second string : Good Afternoon
Strings are Equal
String Concatenate
The string concatenate functions append one string to the end of another. They return the
address pointers to the destination string. The size of the destination string array is assumed to be
large enough to hold the resulting string. If it isn’t the data at the end of the string array are
destroyed.
Basic String Concatenation
The function declaration is as follows
char* strcat(char* str1, const char* str2);
The function copies str2 to the end of str1, beginning with str1’s delimiter. That is ,the delimiter
is replaced with the first character of str2. The delimiter from str2 is copied to the resulting string
to ensure that a valid string results.
/* Program to concatenate two strings using strcat() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf("Enter first string :");
scanf("%s",str1);
printf("Enter second string :");
scanf("%s",str2);
strcat(str1,str2);
printf("Concatenated String = %s",str1);
getch();
}
Output
Enter first string : Data
Enter second string : Structures
Concatenated String : DataStructures
MITS Page 41
CPDS UNIT -III
Output
String Reverse
The reverse of a string can be done by using the function strrev. The function declaration
is as follows
char* strrev(char* string);
/* Program to reverse a string using strrev() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str1[20];
clrscr();
printf("Enter a string :");
scanf("%s",str1);
strrev(str1);
MITS Page 42
CPDS UNIT -III
Character to String
Two string functions search for a character in a string. The first function is called strin
character strchr, it searches for the first occurrence of character from the beginning of the string.
The second string rear character strrchr, searches for the first occurrence beginning at the rear
and working toward the front.
The function declarations for these functions are shown below
char* strchr(const char* string, int ch);
char* strrchr(const char* string, int ch);
/* Program to search character using strrchr() function*/
#include<stdio.h>
#include<string.h>
void main()
{
char str[20]=”This is string”;
char *ptr, c = ‘i’;
clrscr();
ptr = strchr(ptr,c);
if(ptr)
printf(“The character %c is found in position %d”,c, ptr-string);
else
printf(“The character %c is not found”,c);
getch();
}
Output
The character i is found in position 2
MITS Page 43
CPDS UNIT -III
ptr = strstr(str1,str2);
printf(“The substring is %s”,ptr);
}
Output
The substring is national
Array of Strings
Array of strings can be defined as the two dimensional character array. If we want to
arrange few strings in an array it can be done by declaring two dimensional character array
char names[7][20];
The above declarations says that there are 7 rows with 20 columns means 7 strings with each
string a maximum of 20 characters.
/* Program to demonstrate the array of strings */
void main()
{
char names[5][20];
int i;
printf(“Enter 5 names :”);
for(i=0; i<5; i++)
scanf(“%s”,names[i]);
printf(“Given names :\n”);
for(i=0; i<5; i++)
printf(“%s\n”,names[i]);
}
Output
Enter 5 names : Kiran Kumar Karthik Kamal Kapil
Given names :
Kiran
Kumar
Karthik
Kamal
Kapil
It is much easier and more efficient to create a array of string using pointers. Each pointer points
to individual string. In this way each string is independent, but at the same time they are grouped
together through an array.
char* days[7];
/*Program to demonstrate the array of strings */
void main()
{
char* days[7];
int i;
days[0] = “Sunday”;
days[1] = “Monday”;
days[2] = “Tuesday”;
MITS Page 44
CPDS UNIT -III
days[3] = “Wednesday”;
days[4] = “Thursday”;
days[5] = “Friday”;
days[6] = “Saturday”;
printf(“Week days : \n”);
for(i=0; i<7; i++)
printf(“%s\n”,days[i]);
}
Output
Week days :
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
MITS Page 45