Pop(Bpops103) Module 4
Pop(Bpops103) Module 4
: 4
MODULE 4:
R A J E S H \0 Delimiter ‘\0’
0 1 2 3 4 5 6 indicates end of
string
1. String literals
2. String variables
String literals are also known as string constants, is a sequence of characters enclosed by double quotation
marks is called string literals. A string literal is a constant its valuecannot be changed. Some examples are:
Examples: “New Delhi”, “I Love India” etc.
String variables are nothing but character array. Following syntax and examplesillustrates declaring string
variables.
Example: char array_name[ ]= “raj”
1
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
Difference between a single character string and a single character array is:
Single character array takes 1 byte where as single character string occupies twobytes as shown below:
‘A’ 25
Limitations of Strings: One string variable cannot be directly assigned to anotherstring as in the case of
ordinary scalar variables.
Let us say int a=10, b;
b=a; /* is perfectly valid */
But take an example of string initialization:
char name1[ ] = “hello”;
char name2[10 ];
name2=name1; /* This initialization is invalid */
But this initialization can be done using a loop and assigning individual characters of
name1 to name2 as shown below:
void main( )
{
int i;
char name1[ ]= “hello”;
2
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
char name2[5];
for ( i=0; i<5;i++)
{
name2[i] =name1[i];
}
name2[i]= ‘\0’;
}
3
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
Example:
#include<stdio.h>
int main()
{
char a[]= “akash”;
puts(a);
}
o/p: akash
Reading a string using scanf( )
It uses string conversion specifier %s to accept a string data. Following example illustrates it:
char name[20];
scanf(“%s”, name);
Note: while reading strings we needn’t specify address of operator (&) as the character array itself is an
address (i.e name itself is base address of array in the above example)
Disadvantage of reading strings using scanf( ) function is multiple words strings cannot be read. For
example say we have to read NEW DELHI, following scanf( ) reads only NEW and stops.
scanf(“%s”, name);say
input is
N E W D E L H I
N E W
Example:
#include<stdio.h>
int main()
{
char a[10];
printf("enter name");
gets(a);
printf("\nname: ");
printf("%s",a);
}
4
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
Extra:
Edit set Conversion code %[ ]: In addition to %s we can also use edit set conversion code %[ ], which
specifies the type of characters that can be accepted by scanf ( ) function.
For Example say we have to accept only 0-9 digits in a string then edit set code can be
used as follows:
char name[20];
scanf(“%[0123456789]”, name)
NOTE: Suppose we want to skip particular set of characters in a string, then we have to
use:
^ symbol in edit set conversion code. Following example illustrates same:
Example 1:
char name[20];
scanf(“%[^A-Z]”, name)
String taxonomy
• Strings in Pascal is different from strings in C:
• We can store a string either in fixed length format or variable length format.
Fixed-length strings:
When storing a string in a fixed-length format, you need to specify an appropriate size for the string variable. If
the size is too small, then you will not be able to store all the elements in the string. On the other hand, if the
string size is large, then unnecessarily memory space will be wasted.
Variable-length strings:
A better option is to use a variable length format in which the string can be expanded or contracted to
accommodate the elements in it. For example, if you declare a string variable to store the name of a student. If a
5
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
student has a long name of say 20 characters, then the string can be expanded to accommodate 20 characters.
On the other hand, a student name has only 5 characters, then the string variable can be contracted to store only
5 characters. However, to use a variable-length string format you need a technique to indicate the end of
elements that are a part of the string. This can be done either by using length-controlled string or a delimiter.
Length-controlled strings:
In a length-controlled string, you need to specify the number of characters in the string. This count is used by
string manipulation functions to determine the actual length of the string variable.
Delimited strings:
In this format, the string is ended with a delimiter. The delimiter is then used to identify the end of the string.
For example, in English language every sentence is ended with a full-stop (.). Similarly, in C we can use any
character such as comma, semicolon, colon, dash, null character, etc. as the delimiter of a string.
However, null character is the most commonly used string delimiter in the C language. You must be having
some confusion when we use the term string and character array. Basically a string is stored in an array of
characters. If we are using the null character as the string delimiting character then we treat the part of the array
from the beginning to the null character as the string and ignore the rest.
Operations on string:
There are carious operations which can be performed on strings without using build in library functions.
Those operations are listed below.
1. Converting Characters of a String into Upper Case
2. Converting Characters of a String Into Lower Case
3. Appending string to another string
4. Comparing 2 strings
5. Finding length of the string.
6
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
7
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
8
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
4. Comparing 2 strings
A compare function is used to compare two strings. It takes the two strings as a parameter and returns
an integer value based on the relationship between two strings.
9
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
strcpy() does not check to see whether there is room for the resulting string at the specified location. If there
is no room, it copies characters on top of whatever variables follow in memory. This may destroy the
contents of other variables.
2. strlen():the string length function can be used to find the length of the string inbytes.
It takes the form
length=strlen(str);
syntax: strlen(string);
The parameter to strlen, str is a string. The return value length is an integer
representing current length of str in bytes excluding the null character.
Ex: str=”SGBIT” ;
length=strlen(str); //5
str='\0';
length=strlen(str); //0
10
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
3. strcmp( ): A strcmp() is used to compare two strings. It takes the two strings as a
parameter and returns an integer value based on the relationship between two strings.
General form of call to
strcmp(srt1,str2)
result=strcmp(first,second);
result>0 if first> second
result=0 if first==second
result<0 if first<second
Ex: int res;
res=strcmp(“cat”,”car”); //res>0
res=strcmp(“pot”,”pot”);//res=0
res=strcmp(“big”,”little”); //res<0
4. strcat( ): often it is useful to concatenate or join two strings together. The strcat
function is used to join two strings together. The resulting string has only one null
character at the end.
General form of a call to strcat( )
strcat(first, second);
After the call, first contains all the characters from first, followed by the ones from
second up to and including the first null character in second.
Note: strcat stops copying when it finds a null character in the second string. If it
doesn’t find a null character, strcat continues copying bytes from memory until it finds
null character. The programmer must check to make sure that the resulting string fits in
the variable.
11
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
6. strncpy( ): The strncpy function allows us to extract a substring from one string and
copy it to another location.
General form of call to strncpy()
strncpy(dest, source, numchars);
The strncpy function takes three parameters. Here this statement copies the numchars
of the source string in to dest string. Since numchar does not include null character , we
have to place it explicitly in the source string.
Ex: char source[20]=”computer world”;
char dest[10];
strncpy(dest,source,3); //first three characters of source is copied into dest
dest[3]=’\0’; //we have to put null character at the end of dest string
printf(“%s”,dest); //com
12
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
Array of strings: Array of string is an array of one dimensional character array, which
consists of strings as its individual elements.
Declaration of array of strings: char name[size1][size2];
Ex:
char days[7][10]={“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”,”Saturday”};
Pointers
Pointers: A pointer is a variable that holds the address of another variable. The pointer variablecontains
only the address of the referenced variable not the value stored at that address.
Disadvantages of pointers
1. One of the disadvantage of using pointer is that program may crash if sufficient memoryis not
available at run time to store pointers.
Datatype *ptrname;
Data type: It specifies the type of the pointer variable that you want to declare like (int, float,char, double
or void)
* (Asterisk): tells the compiler that you are creating a pointer variable and ptrname specifies the name of
the pointer variable.
13
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
Initialization of pointer variable: Similar to the initialization of other variables at the time of their
declaration, you can also initialize the pointer variable by assigning address of othervariables to them.
Syntax
Datatype *ptrname = expression;
Where,
Datatype: It can be any basic data type,
ptrname is a pointer variable,
expression can be any constant value or any variable containing value.
Example:
Example 1:
int a;
int *ptr = &a; //address of a is stored in ptr variable.
Example 2:
float temp; // temp is a variable of float type
float *p; //p is a ptr variable pointing to float type
p=&temp; // pointer variable p holds the address of temp
#include<stdio.h>void
main()
{
int *ptr; / /declaration of pointer variable
int a=10;
ptr=&a; / /initialization of pointer variable
printf(“the value of a=%d\”,a);
printf(“the value of a using pointer=%d\n”,*ptr);
printf(“the address of a=%u\n”,ptr);
}
Output:
The value of a=10
The value of a using pointer=10
The address of a =32200
Using the address of (&) operator: A computer uses memory to store the instructions of different
programs and the values of different variables. Since memory is a sequential collection of storage cells,
each cell has an address. When you declare a variable, the operating system allocates memory according to
the size of the data type of that variable. In this memory location, the value of the variable is stored.
This statement request the operating system to allocate two bytes of space in memory and stores 100 in
that location.
a ------------ →variable name
100 ---
---------→value of the variable
14
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
By using the address of (&) operator, you can determine the address of a variable.
#include<stdio.h>
void main()
{
int a=100,*ptr1; float
b=12.6, *ptr2;ptr1=&a;
ptr2=&b;
printf(“the address of a = %u and its value is%d\n”,ptr1,*ptr1);
printf(“the address of b =%u and its value is %f\n”,ptr2,*ptr2);
}
Output: the address of a=2600 and its value is 100
The address of b=4876 and its value is 12.600000
15
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
Types of pointers:
1. NULL POINTER:
• We have seen that a pointer variable is a pointer to some other variable of the same data type.
• However, in some cases we may prefer to have null pointer which is a special pointer that does not
point to any value.
• This means that a null pointer does not point to any valid memory address.
• To declare a null pointer you may use the predefined constant NULL, which is defined in several
standard header files including <stdio.h>, <stdlib.h>, and <string.h>.
• After including any of these files in your program, write
int *ptr = NULL;
• You can always check whether a given pointer variable stores address of some variable or contains a
NULL by writing:
if (ptr == NULL)
{
Statement block;
}
• You may also initialize a pointer as a null pointer by using a constant 0, as shown below.
int ptr;
ptr = 0;
2. GENERIC POINTERS
• A generic pointer is a pointer variable that has void as its data type.
• The void pointer, or the generic pointer, is a special type of pointer that can be used to point to variables
of any data type.
• It is declared like a normal pointer variable but using the void keyword as the pointer's data type.
• For example, void *ptr;
• In C, since you cannot have a variable of type void, the void pointer will therefore not point to any data
and thus cannot be dereferenced.
• You need to type cast a void pointer (generic pointer) to another kind of pointer before using it.
• Generic pointers are often used when you want a pointer to point to data of different types at different
times.
For example,
16
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
#include <stdio.h>
int main()
{
int x=10;
char ch = 'A';
void *gp;
gp = &x;
printf("\n Generic pointer points to the integer value = %", * (int*) gp);
gp = &ch;
printf("\n Generic pointer now points to the character = %c", * (char*) gp) ;
}
Example 1
#include<stdio.h>
void swap(int *a, int *b);void
main()
{
int x, y;
x=100;
y=200;
printf(“before swap: x=%d\n y=%d\n”, x,y);
swap(&x, &y);
printf(“after swap: x=%d\n, y=%d\n”, x, y);
}
void swap(int *a, int *b)
{
int temp;temp=*a;
*a=*b;
*b=temp;
}
Output:
Before swap: x=100
y=200
After swap: x=200
y=100
17
First Year Engineering, Sub Name: POP Code: 22POP13 Module No.: 4
Example 2
#include <stdio.h>
#include <conio.h>
void sum (int *a, int *b, int *+);
int main()
{
int num1, num2, total;
printf("\n Enter the first number: ");
scanf ("%d", &num1);
printf("\n Enter the second number: ");
scanf ("%d", &num2); sum (&num1, &num2, &total);
printf ("\n Total = %d", total);
}
void sum (int *a, int *b, int *t)
{
*t = *a + *b;
}
18