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

Unit 4 Complete Autonomous

Uploaded by

22kq1a4719
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Unit 4 Complete Autonomous

Uploaded by

22kq1a4719
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

V.SriHarsha Asst.

Prof Pace ITS


UNIT-IV
Pointers: Definition, initialization, operations on pointers, functions and pointers, arrays
and pointers, pointers to pointers, dynamic memory allocation.
Strings: C Strings, String Input / Output functions, arrays of strings, string manipulation
functions.
Concept of a Pointer: C provides the important feature of data manipulations with the
address of the variables. Hence the execution time is very much reduced. Such concept is
possible with the special data type called pointers.
Definition : A pointer is a variable which stores the address of another variable.
Declaration : Pointer declaration is similar to normal variable but preceded by * symbol.
Here, ‘*’ is known as ‘value at address’ operator or indirection operator. It tells that the variable
is a pointer variable. Datatype indicates the datatype of the value which is stored in the address
location indicated by the pointer variable.

syntax: datatype *identifier;


example: int *p;
char *ch1,*ch2;
int x,y,*p,z;
Initialization : At the time of declaring a pointer, we can store some address into that pointer
is called as initialization of pointer.
Syntax : datatype *identifier = address;
Example :
int a;
int *p;
a=10;
p = &a;
Assigning Address to a pointer:
datatype *identifier;
identifier=Address;
example :int *p;
int a;
p=&a;
program:
void main( )
{
int a=5,*p;
float b=2.5,*q;
char c=’a’,*r;
p=&a;
q=&b;
r=&c;
printf(“a=%d, address of a=%u”,*p,p);
printf(“b=%d, address of b=%u”,*q,q);
printf(“c=%d, address of c=%u”,*r,r);
}
Note : Any type of pointer, it allocates only 2 bytes of memory ,Because it stores the address of
memory location. In C language the memory address is in unsigned integer. (2 bytes for
unsigned int, in the range of 0 to 65535)
1
V.SriHarsha Asst.Prof Pace ITS
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int *p1;
char *p2;
float *p3;
double *p4;
clrscr();
printf("size of int pointer = %d bytes",sizeof(p1));
printf("\nsize of char pointer = %d bytes",sizeof(p2));
printf("\nsize of float pointer = %d bytes",sizeof(p3));
printf("\nsize of double pointer = %d bytes",sizeof(p4));
getch();
}
Output:
size of int pointer = 2bytes
size of char pointer = 2bytes
size of float pointer = 2bytes
size of double pointer = 2bytes
pointer Types: C supports different types pointers those are:
 NULL Pointer
 Generic Pointers
 Wild Pointer
 Dangling Pointer

Null Pointer:
 NULL Pointer is a pointer which is pointing to nothing.
 NULL pointer points the base address of segment.
 In case, if you don’t have address to be assigned to pointer then you can simply use
NULL
 Pointer which is initialized with NULL value is considered as NULL pointer.
Example:
float *ptr=(float *)0;
char *ptr=(char *)0;
double *ptr=(double *)0;
char *ptr=’\0’;
int *ptr=NULL;
program:
#include<stdio.h>
void main()
{
int *ptr=NULL;
printf(“the value of ptr %u”,ptr);
}
Output:
the value of ptr is 0

2
V.SriHarsha Asst.Prof Pace ITS
Generic Pointers : void pointer in c is also known as generic pointer ,the meaning of generic
pointer is a pointer which can point any type of data.
Example:
void *ptr;
here ptr is a generic pointer.
Note:void pointers cannot be dereferenced. For example the following program doesn’t compile.
void main()
{
int a = 10;
void *ptr = &a;
printf("%d", *ptr);
}
Output:
Compiler Error: 'void*' is not a pointer-to-object type
The following program compiles and runs fine.
void main()
{
int a = 10;
void *ptr = &a;
printf("%d", *(int *)ptr);
}
Output:
10

Wild Pointer: A pointer in c which has not been initialized is known as wild pointer.
Example:
# include<stdio.h>
int main(){
int *ptr;
printf("%u\n",ptr);
printf("%d",*ptr);
return 0;
}
Output:
Any address
Garbage value
Dangling Pointer : If any pointer is pointing the memory address of any variable but
after some variable has deleted from that memory location while pointer is still pointing
such memory location. Such pointer is known as dangling pointer and this problem is
known as dangling pointer problem.

Cause of Dangling Pointer in c:


3
V.SriHarsha Asst.Prof Pace ITS
void function()
{
int *ptr=(int *)malloc (SIZE);
……………..
………………
free(ptr);//ptr now becomes dangling pointer
}
In above example we first allocated a memory and stored its address in ptr. After executing few
statements we deallocated the memory. Now still ptr is pointing to same memory address so it
becomes dangling pointer.
How to Solve Dangling Pointer Problem in C?
To solve this problem just assign NULL to the pointer after the deallocation of memory that it
was pointing. It means now pointer is not pointing to any memory address.
void function()
{
int *ptr=(int *)malloc (SIZE);
……………..
………………
free(ptr);//ptr now becomes dangling pointer
ptr=NULL;// now ptr is not dangling pointer
}
Operations on pointers (or) Address Arithmetic: In c pointers can also be
incremented, decremented and manipulated using arithmetic expressions. Since a pointer is a
data type in c, certain operations are allowed on it. The following are the operations that are
possible with pointers:
 A pointer can be assigned to another pointer. This will cause both the pointers point to
the same object.
 A pointer can be incremented / decremented. The result is to cause the pointer to point to
the subsequent/previous element.
 An integer can be added or subtracted from a pointer.
 One pointer can be subtracted from another pointer(but cannot added) provided that they
are pointing the same array. The expression returns the number of elements between
them.
The following arithmetic operations are allowed to use on the pointer type operands.
1. Incrementing a pointer: Each time a pointer is incremented it points to the memory
location of the next element of its base type.
Example : suppose ptr=1002,after the execution of the following statement
ptr++;
the ptr is incremented by 1,that is it becomes 1004 rather than 1003 since the size of int
is 2 bytes, the next address of base type is 1004.
2. Decrementing a pointer: Each time a pointer is decremented it points to the memory
location of the previous element of its base type.
Example : suppose ptr= 1002, after the execution of the following statement
ptr--;
the ptr is decremented by 1,that is it becomes 1000, rather than 1001 since the size of the
int is 2 bytes,the previous address of the base type is 1000.
3. Adding an integer to pointer : let ptr=1002
Consider the statement ptr=ptr+2;

4
V.SriHarsha Asst.Prof Pace ITS
In the above expression when the integer 2 is added to the pointer variable ptr and the ptr
value becomes 1006 rather than 1004. Since the size of the in t is 2 the pointer ptr value is
incremented by 2*sizeof(int)=2*2=4, that is, the value of ptr=1002+4=1006.
4. Subtracting an integer to pointer : let ptr=1004
Consider the following statement ptr=ptr-2;
In the above expression when the integer 2 is subtracted from the pointer variable ptr the
ptr value becomes 1000, rather than 1002. Since the size of the int is 2 the pointer ptr
value is decremented by 2*sizeof(int)=2*2=4, that is value of ptr=1004-4=1000.
The pointer arithmetic on different types shown in below table:

Pointer variable Pointer value Pointer increment Pointer value after


increment
char *a; 10 a++;/++a; 11(a+sizeof(char))
a=a+3; 13(a+sizeof(char)*3)
int *b; 10 b++;/++b; 12(b+sizeof(int))
b=b+2; 14(b+sizeof(int)*2)
long *c; 10 c++;/++c; 14(c+sizeof(long))
c=c+3; 22(c+sizeof(long)*3)
double *e; 10 e++;/++e; 18(e+sizeof(double))
e=e+2; 26(e+sizeof(double)*2)

The following program illustrates the concept of pointer arithmetic


#include<stdio.h>
void main()
{
int i, *iptr;
iptr=&i;
priintf(“iptr=%u \n”,iptr);
iptr++;
printf(“after iptr++ iptr=%u \n”,iptr);
iptr--;
printf(“after iptr-- iptr=%u \n”,iptr);
iptr=iptr+2;
printf(“after iptr+2 iptr=%u\n”,iptr);
iptr=iptr-2;
printf(“after iptr -2 iptr=%u\n”,iptr);
}
Output:
iptr=45524(assume because its not always same)
after iptr++ iptr=45526
after iptr-- iptr=45524
after iptr+2 iptr=45528
after iptr-2 iptr=45524

5
V.SriHarsha Asst.Prof Pace ITS
Functions and pointers
Pointers as function Arguments: pointers provide the two way communication between
the service requester and service provider. It is achieved by passing address of the actual
parameters instead of their contents. Any modification done to formal variables in the function
will be automatically reflected in the actual parameters when they are passed by address.
The below program illustrates this situation:
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{
int x=10,y=20;
swap(&x,&y);
printf(“after swapping \n”);
printf(“x contains %d \n”,x);
printf(“y contains %d\n”,y);
}
void swap(int *a, int *b)
{
temp=*a;
*a=*b;
*b=temp;
}
Output:
after swapping
x contains 20
y contains 10
Pointer to functions
It is possible to declare a pointer pointing to a function which can then be used as an argument in
another function. A pointer to a function is declared as follows,
type (*pointer-name)(parameter);
Here is an example :
int (*sum)(); //legal declaration of pointer to function
int *sum(); //This is not a declaration of pointer to function
A function pointer can point to a specific function when it is assigned the name of that function.
int sum(int, int);
int (*s)(int, int);
s = sum;
Here s is a pointer to a function sum. Now sum can be called using function pointer s along with
providing the required argument values.
s (10, 20);
Example of Pointer to Function
#include <stdio.h>
int sum(int x, int y)
6
V.SriHarsha Asst.Prof Pace ITS
{
return x+y;
}
void main( )
{
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d", s);
}
Output:
Sum is 25
arrays and pointers

 Continuous memory locations are allocated for all the elements of the array by the
compiler
 The base address is the location of the first element (index 0) of the array.
Eg : int a [5] = {10, 20,30,40,50};
The five elements are stored as follows
Elements a[0] a[1] a[2] a[3] a[4]
Value 10 20 30 40 50
Address 1000 1002 1004 1006 1008

base address
a= &a[0]=1000
if ‘p’ is declared as integer pointer, then the array ‘a’ can be pointed by the following assignment

(P+i) =&( a+i);


(or) p = &a[0];
(or) P=a;

 Every value of ‘a’ can be accessed by using p++ to move from one element to another.
When a pointer is incremented, its value is increased by the size of the datatype that it
points to. This length is called the “scale factor”
 The relationship between ‘p’ and ‘a’ is shown below

P = &a[0] = 1000
P+1 = &a[1] = 1002
P+2 = &a[2] = 1004
P+3 = &a[3] = 1006
P+4 = &a[4] = 1008

 Address of an element is calculated using its index and the scale factor of the datatype.

For eg:
7
V.SriHarsha Asst.Prof Pace ITS

Address of a[3] = base address + (3* scale factor of int)


= 1000 + (3*2)
= 1000 +6
= 1006

 instead of using array indexing, pointers can be used to access array elements.
 *(p+3) gives the value of a[3]
*(p+i) = a[i]

Program
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a[10],n;
int *p,i;
clrscr ( );
printf(“enter the size of array=\n”);
scanf(“%d”,&n);
printf (”Enter %d elements=”,n);
for (i=0; i<n; i++)
scanf (“%d”, &a[i]);
p = &a[0];
printf (“Elements of the array are”);
for (i=0; i<n; i++)
printf(“%d”, *(p+i));
getch( );
}
Input
Enter the size of array=5
Enter 5 elements : 10 20 30 40 50
Output
Elements of the array are : 10 20 30 40 50

Pointers and two dimensional arrays :

 Memory allocation for a 2-dimensional array is as follows:


int a[3] [3] = {1,2,3,4,5,6,7,8,9};

a[0] [0] a[0] [1] a[0] [2] a[1] [0] a[1] [1] a[1] [2] a[2] [0] a[2] [1] a[2] [2]

1 2 3 4 5 6 7 8 9
8
V.SriHarsha Asst.Prof Pace ITS

1234 1236 1238 1240 1242 1244 1246 1248 1250

1st row 2nd row 3rd row

base address = 1234 = &a[0] [0]

int *p; Assigning base address to


p = &a[0] [0];
a pointer
(or) p =a

 Pointer is used to access the elements of 2 – dimensional array as follows

a[i] [j] = *(p+i*columnsize+j)

a[1] [2] = *(1234 + 1*3+2)


= *(1234 + 3+2)
= *(1234 + 5*2) Scale factor
= * (1234+10)
= *(1244)
a[1] [2] = 6

Program
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a[3] [3], i,j;
int *p;
clrscr ( );
printf (“Enter elements of 2D array”);
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
scanf (“%d”, &a[i] [j]);
}
}
p = &a[0] [0];
printf (“elements of 2d array are”);
for (i=0; i<3; i++)
{
9
V.SriHarsha Asst.Prof Pace ITS
for (j=0; j<3; j++)
printf (”%d \t”, *(p+i*3+j));
}
printf (“\n”);
}
getch ( );
}
input
enter elements of 2D array
1 2 3 4 5 6 7 8 9
output
Elements of 2D array are
1 2 3
4 5 6
7 8 9

Array of pointers
 It is collection of addresses (or) collection of pointers .
Declaration
datatype *pointername [size];
eg: int *p[5]; It represents an array of pointers that can hold 5 integer element addresses
p[0] p[1] p[2] p[3] p[4]

Initialization
‘&’ is used for initialization
Eg : int a[3] = {10,20,30};
int *p[3], i;
for (i=0; i<3; i++) (or) for (i=0; i<3,i++)
p[i] = &a[i];
p[i]=a+i;

Accessing
Indirection operator (*) is used for accessing
Eg: for (i=0, i<3; i++)
printf (”%d”, *p[i]);

10
V.SriHarsha Asst.Prof Pace ITS
Program
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a[3] = {10,20,30};
int *p[3],i;
for (i=0; i<3; i++)
p[i] = &a[i];
printf (elements of the array are”)
for (i=0; i<3; i++)
printf (”%d \t”, *p[i]);
getch();
}
Output :elements at the array are : 10 20 30

Pointers to Pointers
In c it is possible to have a pointer point to another pointer that points to the target value. This is
called multiple indirection or pointers to pointers. Below fig ,shows the concept of multiple
indirection.

pointer variable

Address value
Single Indirection
Pointer pointer variable

Address Address value

Multiple Indirections

The value of a normal pointer is the address of the variable that contains the desired value. In
case of a pointer to pointer, the first pointer contains the address of the second pointer which
points to the variable that contains the desired value.
Multiple Indirections can be carried on to whatever extent desired, but more than a pointer to a
pointer is rarely needed. In fact, excessive indirection is difficult to follow and prone to
conceptual errors.
A variable that is pointer to a pointer must be declared by placing in additional indirection
operator in front of the variable name. The syntax for double pointer variable is:
data type **ptr;

example is float **ptr;


The following program illustrates the use of pointer-to-pointer concept.
#include<stdio.h>
void main()
{
int i=5;
int *ptr1;
int **ptr2;
11
V.SriHarsha Asst.Prof Pace ITS
ptr1=&i;
ptr2=&ptr1;
printf(“\n value of i is %d stored at=%u”,i,&i);
printf(“\n value of ptr1 is %u stored at=%u”,ptr1,&ptr1);
printf(“\n value of ptrt2 is %u stored at=%u”,ptr2,&ptr2);
printf(“\n value of i=%d”, **ptr2);
}
Output:
value of i is 5 stored at=45524
value of ptr1 is 45524 stored at= 45522
value of ptr2 is 45522 stored at 45520
value of i=5
Dynamic Memory Management Functions: We know the variables are named as
memory locations and they are store data to be manipulated by the program. So far, in all our
programs, memory locations for the variables were allocated during compilation time itself. For
example the declarations int a;float b;and char c; tells the compiler to allocate two bytes, four
bytes and one byte of memory respectively. So the amount of memory is determined by the
compiler itself depending on the type of variables. This type of memory allocation is called as
static memory allocation.

For example the declaration of arrays in c:


int x[5];
declares x to be an array of int type and size 5. The compiler thus allocates 5 contiguous memory
location to the array x. These memory locations are allocated for array statically. Here we
identify two problems.
 Firstly, if we need to deal with more than five values of int type during runtime of the
program, we cannot increase the size of array during runtime.
 Secondly , sometimes not all locations are used in the array when this is the case, we can
not decrease the size of array. As a result memory goes wasted.
To resolve such kinds of problems dynamic memory allocation comes in to picture. As the
name itself indicates, memory can be allocated dynamically i.e., during runtime of the programs.
While allocating we can specify the size of the memory block to be allocated and also we can
release the unwanted memory blocks for later use. The standard c library has the following four
built-in functions, which help in dealing with the dynamic memory allocation.
TABLE: Memory Allocation Functions
Function Name Purpose
malloc() Allocates the required size of bytes and returns the pointer to the first
byte of the allocated space.
calloc() Allocates space for an array of elements, initializes them to zero and
then returns a pointer to the memory.
free() Frees previously allocated space.
realloc() Modifies the size previously allocated space.

malloc(): The malloc() allocates a block of memory of requested size and returns a pointer to
the first byte of the block.
syntax of malloc(): ptr=(data_type*)malloc(byte_size);

12
V.SriHarsha Asst.Prof Pace ITS
whre byte_size is the number of bytes to be allocated and ptr is a pointer of type data-type, which
collects the address of the first byte of memory block allocated. The memory block allocated will
have garbage values. If there is not enough space , a NULL pointer is returned.
Example: int *p;
p=(int *)malloc(5*(sizeof(int));

p 1024 1026 1028 1030 1032

1024

free(): The free() is to release a block of memory, which is previously allocated so that it can be
reused for some other purpose.

The syntax is free(ptr);

Where ptr is a pointer, which points to the first byte of the memory block to be released.
Example: int *p;
p=(int *)malloc(5*(sizeof(int));
free(p);
Program: To illustrate malloc(): Creation of an array dynamically
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
void main()
{
int *iptr,n,i;
printf(“enter number of elements \n”);
scanf(“%d”,&n);
iptr=(int *)malloc(n*sizeof(int)); /* allocate memory for n integers */
printf(“enter %d elements \n”,n);
for(i=0;i<n;i++)
scanf(“%d”,iptr+i);
printf(“the list of elements \n”);
for(i=0;i<n;i++)
printf(“%d\n”, *(iptr+i));
free(iptr); /* release allocated memory */
}
Output:
Enter number of elements
4
Enter 4 elements
10 20 30 40
The list of elements
10 20 30 40
calloc(): The calloc() allocates multiple blocks of memory, all of which are of same size and
returns a pointer to the first byte of the first block.
The Synatx is Ptr=(data_type*)calloc(n,block_size);

13
V.SriHarsha Asst.Prof Pace ITS
Where n is the number of blocks of memory to be allocated , block_size is the number of bytes in
each block and ptr is a pointer of type data-type, which collects the address of the first byte of the
first memory block allocated. The memory block allocated will be filled with zeros. If there is
not enough space, a NULL pointer is returned.
Example:
int *p;
p=(int *) calloc (10,sizeof(int));

p 1024 1026
1024 0 0 …………………

Program: To illustrate calloc() : Creation of array dynamically


#include<stdio.h>
#include<conio.h>
#include<malloc.h>
void main()
{
int *iptr,n,i;
printf(“enter number of elements \n”);
scanf(“%d”,&n);
iptr=(int *)calloc(n,sizeof(int)); /* allocate memory for n integers */
printf(“enter %d elements \n”,n);
for(i=0;i<n;i++)
scanf(“%d”,iptr+i);
printf(“the list of elements \n”);
for(i=0;i<n;i++)
printf(“%d\n”, *(iptr+i));
free(iptr); /* release allocated memory */
}

Output:
Enter number of elements
4
Enter 4 elements
10 20 30 40
The list of elements
10 20 30 40
realloc() : we know that malloc() and calloc() are used to dynamically allocate memory space
required to store data. Under some situations, we may need to change the size of memory block
allocated by either malloc() and calloc(),during runtime itself. This is accomplished by realloc().
Syntax:
New_ptr=(data_type *) realloc(old_ptr,new_size);

Where old_ptr point to the block of memory previously allocated by malloc() or calloc(),
new_ size is the size of the block to be reallocated. Here new_size may be smaller or larger than
the earlier size of the memory block. The position of the old memory block and that of
reallocated block may be same or different. If they are different, the data in the old block will be
safely shifted to the new block.
Example: int *p;
14
V.SriHarsha Asst.Prof Pace ITS
p=(int *)malloc(10* sizeof (int));
p=(int *) realloc (p,10);
Note:%p is used to print pointer addresses.
Program: To illustrate realloc() and free()
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<malloc.h>
void main()
{
char *name;
name=(char *)malloc(10* sizeof (char));
strcpy(name,”Vijyawada”);
printf(“Name %s is at address %p”,name,name);
name=(char *)realloc(name,14 * sizeof (char));
strcpy(name, “Andhrapradesh”);
printf(“Name %s is at address %p \n”,name,name);
free(name);
}
Output:
Name Vijyawada is at address 06EA
Name Andhrapradesh is at address 06F9
Differences between malloc() and calloc() functions:
malloc() calloc()
malloc() allocates the required size of bytes calloc() allocates memory for an array of
and returns pointer to first byte elements initializes them to zero and returns
pointer to first byte.
malloc() allocates bytes of memory. calloc() allocates blocks memory.
malloc() takes single argument which calloc() takes two arguments which are
determines memory required in bytes. number of elements to allocate memory and
size in bytes of a single variable.
malloc() does not initialize the memory calloc() initializes the memory blocks with
blocks while allocating. zero while allocating.
Syntax: Ptr=(data_type*)malloc(n*block_size); Syntax: Ptr=(data_type*)calloc(n,block_size);

Command Line Arguments: It is possible to pass some values from the command line to
the C programs when they are executed. These values are called command line arguments.
The command line arguments are handled using main() function.
(or)
In c programs it is important to note that we can pass parameters to main() also. If the main() is
to be defined to accept parameters, the actual parameters should be provided from the command
prompt itself .Hence these parameters are called command line parameters or command line
arguments.

15
V.SriHarsha Asst.Prof Pace ITS
To make the main() of a program take the command line parameters, the function header will
have the following syntax:
void main( int argc, char *argv[] )

argc and argv[] are the command line arguments(formal parameters) which are passed to the
main function. Here argc refers to the number of arguments passed, and argv[] is a character
pointer array which points to each argument passed to the program.
Example Program:
#include<stdio.h>
#include<ctype.h>
void main(int argc, char * argv[])
{
int i, sum = 0;
if (argc != 3)
{
printf("You have forgot to type numbers.");
exit(1);
}
printf("The sum is : ");
for (i = 1; i < argc; i++)
sum = sum + atoi(argv[i]);
printf("%d", sum);
}
Save the program as add.c and compile the program then we can get the executable add.exe ,run
that executable from command prompt like as below:
C:\Turboc\add 10 20
Output: The sum is 30

Strings
String Def: A String is defined as an array of characters. Or Sequence (group) of characters
enclosed within double quotes is called as a string constant.
Declaration & initialization of strings:
Syntax: char stringname[size];
Size is the number of characters in the string.
Ex: char name[10];
char address[20];
When the compiler assigns a character string to a character array, it automatically places a null
character \0 (\zero) at the end of the string. Hence, the size should be equal to maximum number
of characters in the string plus one.
Character arrays can be initialized when they are declared.
char name[8] ={‘c’,’o’,’l’,’l’,’e’,’g’,’e’,’\0’};
When we initialize a character array by listing its elements, we must explicitly place a null
character.
char name[8]=”college”;
In this declaration \0 is not necessary, C language inserts a null character automatically.
The elements of character array are stored in contiguous memory locations.
name[0] name[1] name[2] name[3] name[4] name[5] name[6] name[7]
16
V.SriHarsha Asst.Prof Pace ITS
c o l l e g e \0

6518 6519 6520 6521 6522 6523 6524 6525

String Input and Output:


Strings can be read and displayed using some standard library functions. Those are
Input functions Output functions
scanf() printf()
gets() puts()
getchar() putchar()

scanf() and printf():The strings can be read by scanf() function, and %s is the format specifier
and printf() is used to display the data. While using the scanf(), the length of string should not
exceed the dimension of character array. The drawback of scanf() is not capable of receiving
multiword strings.
Ex: Dennis Ritchie
It accepts only Dennis. To overcome this we use functions gets() and puts();
Ex: main(){
char name[30];
printf(“Enter your name ”);
scanf(“%s”,name);/* & is not required while reading a string */
printf(“your name is %s”,name);
}
Output: Enter your name
Dennis Ritchie
your name is Dennis
gets() and puts(): gets() is a simple function that overcomes the drawback of scanf() and gets()
is working as same as printf() function.
Synatx for gets(): gets(str);
Synatx for puts(); puts(str);
Example program is:
Ex: main(){
char name[30];
printf(“Enter your name ”);
gtes(name);//function to read a string from user.
puts(name);//function to display a string.
}
Output: Enter your name
Dennis Ritchie
your name is Dennis Ritchie
getchar() and putchar(): getchar() function is used to read a string but it can read only one
character at a time from entered string. If we want to read the entire string by using this
function ,that has to be executed repeatedly. putchar() is also can display one character at a time.
To display all characters in a string ,it has to be executed repeatedly.
Example:
#include<stdio.h>
17
V.SriHarsha Asst.Prof Pace ITS
void main()
{
char ch;
printf(“enter a string”);
ch=getchar();
putchar(ch);
}
Output:
Enter a string : pace
p
Example:
#include<stdio.h>
void main()
{
char string[20]=”hello world”;
int i=0;
while(string[i]!=’\0’)
{
putchar(string[i]);
i++;
}
}
Output:-
hello world

Arrays of strings:
A string is a 1-D array of characters, so an array of strings is a 2-D array of characters.
Just like we can create a 2-D array of int, float etc; we can also create a 2-D array of character or
array of strings. Here is how we can declare a 2-D array of characters.
char ch_arr[3][10] = {
{'s', 'p', 'i', 'k', 'e', '\0'},
{'t', 'o', 'm','\0'},
{'j', 'e', 'r', 'r', 'y','\0'}
};
It is important to end each 1-D array by the null character otherwise, it's just an array of
characters. We can't use them as strings.
Declaring an array of string this way is a tedious and error-prone process that's why C provides a
more compact way to it. This above initialization is equivalent to:
char ch_arr[3][10] = {
"spike",
"tom",
"jerry"
};
The first subscript of the array i.e 3 denotes the number of strings in the array and the
second subscript denotes the maximum length of the each string. Recall the that in C, each
character occupies 1 byte of data, so when the compiler sees the above statement it
allocates 30 bytes (3*10) of memory.
Example Program:
#include<stdio.h>
18
V.SriHarsha Asst.Prof Pace ITS
#include<conio.h>
void main()
{
char str[10][10];
int i=0,n;
clrscr();
printf("enter no.of strings\n");
scanf("%d",&n);
printf("enter %d strings",n);
for(i=0;i<n;i++)
scanf("%s",str[i]);
printf("the entered strings are:\n");
for(i=0;i<n;i++)
printf("%d=%s\n",i+1,str[i]);
getch();
}
Output:

Arrays of pointers: (to strings)


It is an array whose elements are pointers to the base address of the string.
It is declared and initialized as follows
char *a[ ] = {“one”, “two”, “three”};
Here, a[0] is a pointer to the base address of the string “one”.
a[1] is a pointer to the base address of the string “two”.
a[2] is a pointer to the base address of the string “three”.

o n e \0 t w o \0 t h r e e \0

1234 1238 1242

a[0] 1234
a[1] 1238
a[2] 1242
Array of pointers
Advantage :
19
V.SriHarsha Asst.Prof Pace ITS
Unlinke the two dimensional array of characters. In (array of strings), in array of pointers to
strings there is no fixed memory size for storage.
The strings occupy only as many bytes as required hence, there is no wastage of space.

Program
#include<stdio.h>
#include<conio.h>
#include <string.h>
void main ( )
{
char *a[5] = {“one”, “two”, “three”, “four”, “five”};
int i;
clrscr ( );
printf ( “the strings are”);
for (i=0; i<5; i++)
printf (“%s”, a[i]);
getch ( );
}
Output
The strings are : one two three four five
String Processing:
The strings can be processed by following common operations those are:
1. Reading and writing strings
2. Combining strings together(concatenation)
3. Copying one string to another
4. Compare strings for equality
5. Extracting a portion of a string
6. Convert strings in to uppercase
7. Convert strings into lower case
8. String deletion
9. String replacement . e,.tc

The above mentioned operations can be done with String Library functions and without String
Library functions. The String Library functions are provided by string.h header file so we need to
include this header file in programs if we are using string library functions:

String Library / Manipulation functions:


The following table shows String Handling functions which are provided by string.h header file.

strlen() Finds the length of the string


strcpy() Copies one string into another
strncpy() Copies first n characters of one string into another
strcmp() Compares two strings
stricmp() Compares two strings without regard to case(lower case or upper case)
strncmp() Compares first n characters of two strings
strnicmp() Compares first n characters of 2 strings without regard to case
strlwr() Converts a string to lower case
strupr() Converts a string to upper case
20
V.SriHarsha Asst.Prof Pace ITS
strdup() Duplicates a string
strchr() Finds first occurrence of a given character in a string
strrchr() Finds the last occurrence of a given character in a string
strstr() Finds the first occurrence of a given string in another string
strcat() To concatenate two strings
strncat() Appends first n characters of a string at the end of the other
strrev() Reverses the string
strset() Sets all the characters of a string to a given character
strnset() Sets first n characters of a string to a given character
strspn() Finds up to what length two strings are identical
strpbrk() Searches for the first occurrence of the character in a given string and then
displays string starting from that character

strlen(): This function counts the number of characters present in a string.


Syntax: int variable=strlen(string);

strcpy(): This function copies the contents of one string into another.
Syntax: strcpy(targetstring, sourcestring);
here, the target string should be big enough to hold the source string.
strncpy(): This function copies a specified length of characters from source to destination string.
Syntax: strncpy(targetstring, sourcestring, numberofcharacters);
strcmp(): this function compares two strings to find out whether they are same or different. The
two strings are compared character by character until there is a mismatch or end of the strings is
reached, which ever occurs first.
If the two strings are identical strcmp() returns zero
if the first string is alphabetically before the second string, negative value is returned.
If the second string is alphabetically before the first string , positive value is returned.
Any non-zero means there is a mismatch.
stricmp(): This function compares two strings. The characters of the string may be in the
lowercase or uppercase, this function compares two strings without case.
If the strings are identical it returns zero otherwise it returns a non-zero value.
strncmp(): comparison is made up to a specified length.
Syntax: strncmp(sourcestring , targetstring, argument);
argument is the number of characters up to which the comparison is to be made.
strncmp(char *source, char *target, int argument);

strnicmp():Compares first n characters of 2 strings without regard to case.

strcat() : This function concatenates the source string at the end of target string or it joins the
strings together.

Syntax: strcat(target,source);
here, the target string should be big enough to hold the source string.
Ex: Write a C program to initialize two strings “pace” and “college” and concatenate both the
strings and display the final result as “pace college”
21
V.SriHarsha Asst.Prof Pace ITS
strncat(): Synatx: strncat(char*text1, char* text2,int n);
where n is the number of characters to append.

strlwr(): This function is used to convert any string to a lower case.


Syntax: strlwr(char *string);

strupr(): This function is used to convert the string into uppercase


Syntax: strupr(char *string);

strdup(): This function is used for duplicating a given string at the allocated memory which is
pointed by a pointer variable.
Syntax: char* strdup(char* string);

strchr(): This function returns the pointer to the first occurrence of a given character in the
string from begining.
Syntax: characterpointer = strchr(char *string, char ch);

strrchr(): This function searches for the occurrence of character from the end.
strstr(): this function finds the second string in the first string. It returns the pointer location
from where the second string starts in the first string. If the string is not found, it returns the
NULL character.
Syntax: strstr(char *string1, char *string2);

strrev(): This function is used to print the characters of the given string in the reverse order.
Syntax: strrev(string);

Ex: Write a C program to read a string and print it in the reverse order.
strset(): this function replaces every character of a string with the given character.
strset(char *string, char replace)
here, replace is the character with which we want to replace.

strnset(): this function is used to replace the specified number of characters with a specified
character.
strnset(char* string, char replace, int n);
where, n is the number of characters to be replaced.

Example programs with using string library functions:


Length:
#include <stdio.h>
#include <string.h>
void main()
{
char a[100];
22
V.SriHarsha Asst.Prof Pace ITS
int length;
printf("Enter a string to calculate it's length\n");
gets(a);
length = strlen(a);
printf("Length of entered string is = %d\n",length);
}
Enter a string to calculate it's length
Pace
Length of entered string is =4
Copy:
#include <stdio.h>
#include <string.h>
void main()
{
char str1[20];
char str2[20];
printf(“enter the string1”);
gets(str1);
strcpy(str2,str1);
printf(“copied string :%s \n”,str2);
}
Output:
enter the string1
eeebranch
copied string
eeebranch
Comparison:
#include <stdio.h>
#include <string.h>
void main()
{
char str1=”abcd”, str2[]=”abCd”, str[3]=”abcd”;
int result,result1;
result=strcmp(str1,str2);
printf(“result=%d”,n);
result1=strcmp(str1,str3);
printf(“result1=%d”,result1);
}
Output:
result= 32
result=0
Concatenate:
#include <stdio.h>
#include <string.h>
void main()
{
char str1=”college”, str2[]=”pace”;
strcat(str2,str1)
printf(“concatenated string str2=%s”,str2);
23
V.SriHarsha Asst.Prof Pace ITS
}
Output:
concatenated string str2=pace college
Lower and Upper:
#include <stdio.h>
#include <string.h>
void main()
{
char str1=”college”, str2[]=”PACE”;
printf(“%s \n”,strupr(str1));
printf(“%s \n”strlwr(str2));
}
Output:
COLLEGE
pace
Reverse:
#include <stdio.h>
#include <string.h>
void main()
{
char str1=” PACE”;
printf(“%s \n”,strrev(str1));
}
Output:
ECAP.
String Palindrome or not:
#include <stdio.h>
#include <string.h>
void main()
{
char str1[50],str2[50];
puts(“enter str1”);
gets(str1);
strcpy(str2,str1);
strrev(str2);
if(strcmp(str1,str2)==0)
printf(“the string is palindrome”);
else
printf(“the string is not palindrome”);
}

Output:
Enter str1 MADAM
The string is palindrome.
Implementation of string manipulation operations with library functions
i) copy ii) concatenate iii) length iv) compare

Program:
#include<stdio.h>
24
V.SriHarsha Asst.Prof Pace ITS
#include<string.h>
void main()
{
char str1[30]="students";
char str2[30];
char str3[30]="pace";
char str4[30]="computer";
char str5[30]="computer";
strcpy(str2,str1);
printf("%s\n",str2);
strcat(str3,str2);
printf("%s\n",str3);
if(strcmp(str4,str5)==0)
printf("they are equal\n");
else
printf("not equal");
printf("%d\n",strlen(str5));
}
Output:
students
pacestudents
they are equal
8

Example programs for without using string library functions:


1. reverse
main(){
char str[20],rev[20];
int i,len=0;
printf(“Enter a Line of Text\t”);
gets(str);
for(i=0;str[i]!=’\0’;i++)
len++;
len=len-1;
for(i=0;str[i]!=’\0’;i++)
rev[i]=str[len-i];
rev[i]=’\0’;
printf(“Reverse string is \t”);
puts(rev);
}
2) copy
Program:
#include<stdio.h>
void main()
{
char str1[20],str2[20];
int i=0;
printf("enter a string \n");
25
V.SriHarsha Asst.Prof Pace ITS
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
{
str2[i]=str1[i];
}
str2[i]='\0';
printf("copied string is:%s\n",str2 );
}
Output:
enter a string
harsha
copied string is:harsha

3) concatenate
Program:
#include<stdio.h>
void main()
{
char str1[25],str2[25];
int i=0,j=0;
printf("\nEnter First String:");
scanf("%s",str1);
printf("\nEnter Second String:");
scanf("%s",str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}
Output:
Enter First String:pace
Enter Second String:college
Concatenated String is pacecollege

4) length
Program:
#include<stdio.h>
void main()
{
char str[20];
int i=0;
printf ("enter a string\n");
scanf("%s",str);
26
V.SriHarsha Asst.Prof Pace ITS
while(str[i]!='\0')
i++;
printf("the length of given string is %d",i);
}
Output:
enter a string
pace
the length of given string is 4
5) compare

Program:
#include<stdio.h>
void main()
{
char str1[10],str2[10];
int i,t=0;
printf("enter 1st string \n");
scanf("%s",str1);
printf("enter 2nd string \n");
scanf("%s",str2);
for(i=0;str1[i]!='\0';i++)
{
if(str1[i]!=str2[i])
{
t=1;
break;
}
}
if(t==1)
printf("the strings are not equal \n");
else
printf("strings are equal \n");
}
Output:
enter 1st string
harsha
enter 2nd string
harsha
strings are equal
Palindrome:
#include <stdio.h>
#include <conio.h>
main()
{
char s1[20];
int i, j, len=0, flag=0;
printf("\nEnter any string: ");
gets(s1);
for (i=0; s1[i]!='\0'; i++)
27
V.SriHarsha Asst.Prof Pace ITS
len++;
i = 0;
j = len-1;
while (i < len)
{
if (s1[i] != s1[j])
{
flag = 1;
break;
}
i++;
j--;
}
if (flag == 0)
printf("\nString is palindrome");
else
printf("\nString is not palindrome");
getch();
}

Output:
Enter any string: MADAM
String is palindrome

/* program to count no.of characters,alphabets,words and lines in a text


void main()
{
char str[80];
int lines=1,words=0,alphabets=0,i=0;
clrscr();
printf("enter a text and press 'z' to terminate:\n");
scanf("%[^z]",str);
while(str[i]!='\0')
{
if((str[i]>='A')&&(str[i]<='Z')||(str[i]>='a')&&(str[i]<='z'))
alphabets++;
if((str[i]==' ')||(str[i]=='\n'))
words++;
if(str[i]=='\n')
lines++;
i++;
}
printf("characters=%d\n",i);
printf("alphabets=%d\n",alphabets);
printf("words=%d\n",words);
printf("lines=%d\n",lines);
getch();
}
28
V.SriHarsha Asst.Prof Pace ITS
Output:
enter a text and press 'z' to terminate
we are all in eee
from pace college ^z
characters =37
alphabets=29
words=8
lines 2

/* write a program to replace the specified substring in to the


given string*/
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[10],str2[10];
int p,i;
clrscr();
printf("enter a string \n");
gets(str1);
printf("enter a sub string \n");
gets(str2);
printf("enter position for substring \n");
scanf("%d",&p);
for(i=0;str2[i]!='\0';i++)
{
str1[p]=str2[i];
p++;
}
printf("the string after replacement \n");
puts(str1);
getch();
}
Output:
enter a string : This is your computer
enter sub string : my
enter position for substring : 8
the string after replacement : This is my computer
/*write a program to insert the specified substring into given string */
#include<stdio.h>
void main()
{
char str1[10],str2[10];
int i,p,l1=0,l2=0,n;
clrscr();
printf("enter a string :");
gets(str1);
printf("enter a substring :");
gets(str2);
29
V.SriHarsha Asst.Prof Pace ITS
printf("enter a position for substring :");
scanf("%d",&p);
for(i=0;str1[i]!='\0';i++)
l1++;
for(i=0;str2[i]!='\0';i++)
l2++;
n=l1;
for(i=l1+l2;i>=n;i--)
{
str1[i]=str1[l1];
l1--;
}
for(i=0;str2[i]!='\0';i++)
{
str1[p]=str2[i];
p++;
}
printf("the string after insertion :");
puts(str1);
getch();
}
Output: enter a string : India is country
enter a substring : our
enter a position for substring: 9
the string after insertion : India is our country

Character operations
Character : it can be a character (A-Z(or) a- z);
digit (0-9), a white space, special symbol
Declaration
char a= ‘A’; using a ouput functions character constant.
Character input / ouput functions
input functions printf ( )
scanf ( ) putchar ( )
getchar ( ) putch ( )
getch ( )
getche ( )
eg: char a;
scanf(“%c”, &a); printf (“%c”, &a);
a = getchar ( ); putchar (a);
a = getch ( ); putch (a);

30
V.SriHarsha Asst.Prof Pace ITS

Character analysis and conversion functions


There are some predefined functions available in “ctype.h” library for analyzing the character
input and converting them.

Analysis functions
Function Checks whether entered character is
1. isalpha ( ) An alphabet (or) not
2. isdigit ( ) A digit (or) not
3. isspace ( ) A space, a newline (or) tab
4. ispunct ( ) A special symbol (or) not
5. islower ( ) A lower case letter of alphabet
6. isupper ( ) An upper case letter of alphabet

Converting functions
Function
tolower ( ) Converts an upper case alphabet to lower case

toupper ( ) Converts a lower case alphabet to upper case

Program
#include<stdio.h>
#include<conio.h>
#include <ctype.h>
Void main ( )
{
char a = ‘D’;
clrscr ( );
if ( isalpha (a))
printf ( “%c is an alphabet”,a);
else
printf (“%c is not an alphabet”,a);
getch ( );
}
Output
D is an alphabet

31
V.SriHarsha Asst.Prof Pace ITS

String to number and number to string conversion


There are 2 functions available for conversion. They are:
1) sscanf( ) - used for converting string to number
2) sprintf ( ) - used for converting number to string
1) string to number converstion
sscanf ( ) – takes a string as an input and converts it into numbers
Syntax:
sscanf (string name, “ control string”, variable list);
for eg: a 02 01 2010 - i/p
%s

day month year


- o/p
%d %d %d

02 01 2010

Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ( )
{
char a[20] = “02 01 2010”;
int day, mon, yr;
clrscr( );
sscanf (a, “%d%d %d”, &day, &mon, &yr);
printf ( “Day =%d”, day);
printf ( “Month = %d”, mon);
printf ( “Year = %d”, yr);
getch ( );
}
Output
Day = 02
Month = 01
Year = 2010

32
V.SriHarsha Asst.Prof Pace ITS

2. Number to string conversion


sprintf( ) takes different numeric values as input and converts it into a single string
Syntax :
sprintf ( string name, “control string”, variable list);

for eg: 02 01 2010 - - i/p


%d %d %d

- o/p

%s
Program 02/01/2010

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ( )
{
char a[50];
int day = 11, mon = 12, yr = 2014;
clrscr( );
sprintf (a, “%d/%d/%d”, day, mon, yr);
printf ( “today’s date =%s”, a);
getch ( );
}
Output
Today’s date is 02/01/2010.

33

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy