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

POP Module-4

Module 4 covers strings and pointers in C programming, defining strings as null-terminated character arrays and explaining their operations, including reading, writing, and manipulating strings. It discusses fixed-length and variable-length strings, string operations such as concatenation and comparison, and introduces various string manipulation functions from standard libraries. The module also includes examples of declaring arrays of strings and demonstrates how to read and print multiple strings.

Uploaded by

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

POP Module-4

Module 4 covers strings and pointers in C programming, defining strings as null-terminated character arrays and explaining their operations, including reading, writing, and manipulating strings. It discusses fixed-length and variable-length strings, string operations such as concatenation and comparison, and introduces various string manipulation functions from standard libraries. The module also includes examples of declaring arrays of strings and demonstrates how to read and print multiple strings.

Uploaded by

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

Module 4 Strings & Pointers

Strings: 13.1 Introduction.13.2 String taxonomy.13.3 Operations on strings.13.4


Miscellaneous string and character functions 13.5 Arrays of strings. 14.1 Introduction.14.2
Declaring Pointer Variables.14.3 Types of Pointer.14.4 Passing Arguments to Function
Using Pointers.
[Type here]
MODULE 4
Strings
4.1 Introduction
✓ “A string is a sequence of characters enclosed within double quotes”. or
✓ “String is an array of characters and terminated by NULL character which is denoted by ‘\0’.
✓ In C, a string is a null-terminated character array.
✓ This means that after the last character, a null character ('\0') is stored to signify the end of the
character array.
For example, if we write char str[] = "HELLO";
we are declaring an array that has five characters, namely, H, E, L, L, and O. Apart from these characters,
a null character ('\0') is stored at the end of the string. So, the internal representation of the string becomes
HELLO'\0'. To store a string of length 5, we need 5 + 1 locations (1 extra for the null character). The
name of the character array (or the string) is a pointer to the beginning of the string.
✓ Figure 4.1 shows the difference between character storage and string storage.

✓ If we had declared str as


char str[5] = "HELLO";
then the null character will not be appended automatically to the character array. This is because str can
hold only 5 characters and the characters in HELLO have already filled the space allocated to it.
✓ Like we use subscripts (also known as index) to access the elements of an array, we can also use
subscripts to access the elements of a string. The subscript starts with a zero (0). All the characters
of a string are stored in successive memory locations. Figure 4.2 shows how str[] is stored in the
memory.

1
[Type here]
✓ ASCII code of a character is stored in the memory and not the character itself. So, at address 1000, 72
will be stored as the ASCII code for H is 72. The statement char str[] = "HELLO";
Syntax:
the general form of declaring a string is
char str[size];
✓ The other way to initialize a string is to initialize it as an array of characters. For example,
char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};
Here, the compiler will automatically calculate the size based on the number of characters.
✓ We can also declare a string with size much larger than the number of elements that are initialized.
For example, consider the statement below.
char str [10] = "HELLO";
In such cases, the compiler creates an array of size 10; stores "HELLO" in it and finally terminates
the string with a null character. Rest of the elements in the array are automatically initialized to NULL
✓ Now consider the following statements:
char str[3];
str = "HELLO";
The above initialization statement is illegal in C and would generate a compile-time error.

4.1.1 Reading Strings


✓ If we declare a string by writing char str[100]; Then str can be read by the user in three ways:
1. using scanf function,
2. using gets() function, and
3. using getchar(),getch()or getche() function repeatedly.

using scanf()
✓ Strings can be read using scanf() by writing scanf("%s", str);
✓ Unlike int, float, and char values, %s format does not require the ampersand before the variable str.
✓ The main pitfall of using this function is that the function terminates as soon as it finds a blank
space. Therefore we cannot read the complete sentence using scanf() function.

using gets()
✓ The string can be read by writing gets(str);
✓ gets() is a simple function that overcomes the drawbacks of the scanf() function.
✓ gets() function is used to read a sequence of characters (string) with spaces in between.
✓ The ‘gets()’ function allows us to read an ‘entire line’ of input including whitespace characters.
✓ The gets() function takes the starting address of the string which will hold the input.
✓ The string inputted using gets() is automatically terminated with a null character.

using getchar()
✓ Strings can also be read by calling the getchar() function repeatedly to read a sequence of single
characters (unless a terminating character is entered) and simultaneously storing it in a character
array as shown below:
i=0;
ch = getchar;// Get a character
while(ch != '*')
{
str[i] = ch;// Store the read character in str
i++;
ch = getchar();// Get another character
}
str[i] = '\0';// Terminate str with null character
2
[Type here]
4.1.2 Writing Strings
✓ Strings can be displayed on the screen using the following three ways:
1. using printf() function
2. using puts() function, and
3. using putchar() function repeatedly.

using printf()
✓ Strings can be displayed using printf() by writing printf("%s", str);
✓ We use the format specifier %s to output a string. Observe carefully that there is no ‘&’ character
used with the string variable.
✓ We may also use width and precision specifications along with %s.
✓ The precision specifies the maximum number of characters to be displayed, after which the string is
truncated. For example, printf ("%5.3s", str); The above statement would print only the first three
characters in a total field of five characters. Also these characters would be right justified in the
allocated width.
✓ To make the string left justified, we must use a minus sign. For example, printf ("%–5.3s", str);

using puts()
✓ A string can be displayed by writing puts(str);
✓ puts() is a simple function that overcomes the drawbacks of the printf() function.
✓ The puts() function writes a line of output on the screen. It terminates the line with a newline
character (‘\n’).

using putchar()
✓ Strings can also be written by calling the putchar() function repeatedly to print a sequence of
single characters.
i=0;
while(str[i] != '\0')
{
putchar(str[i]);// Print the character on the screen
i++;
}

4.2 String Taxonomy


✓ In C, we can store a string either in fixed-length format or in variable-length format as shown in
Figure 13.4.

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

3
4.2.2 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 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.
1. Length-controlled strings: In a length-controlled string, you need to specify the number of
characters in the string.
2. Delimited strings: In this format, the string is ended with a delimiter such as comma, semicolon,
colon, dash, null character etc. The delimiter is then used to identify the end of the string.

4.3 Operations on Strings


1. Finding Length of a String
✓ The number of characters in a string constitutes the length of the string. For example,
LENGTH("C PROGRAMMING IS FUN") will return 20. Note that even blank spaces are counted as
characters in the string.
✓ Figure 4.3 shows an algorithm that calculates the length of a string. In this algorithm, I is used as an
index for traversing string STR. To traverse each and every character of STR, we increment the value
of I. Once we encounter the null character, the control jumps out of the while loop and the length is
initialized with the value of I.

int strlength(char str[50])


{
int i=0;
while(str[
i]!=’\0'){
i++;
}
return i;
}
2. Concatenating Two Strings to Form a New String
✓ If s1 and s2 are two strings, then concatenation operation produces a string which contains
characters of s1 followed by the characters of s2.
void strconcat(char str1[50],char str2[50])
{
int i=0,l; l=strlength(str1);
while(str2[i]!=’\0')
{
str1[l+i]=str2[i];
i++;
}
str1[l+i]=’\0';
}

3. Comparing Two Strings


✓ If S1 and S2 are two strings, then comparing the two strings will give either of the following
results:
(a) S1 and S2 are equal
(b) S1>S2, when in dictionary order, S1 will come after S2
(c) S1 <S2, when in dictionary order, S1 precedes S2
✓ To compare the two strings, each and every character is compared from both the strings. If all the
characters are the same, then the two strings are said to be equal.
int strcompare(char str1[50],char str2[50])
{
int i=0, k; while(str1[i]==str2[i])
{
if(str1[i]==’\0')
{
break;
}
i++;
}
k=str1[i]-str2[i];return k;
}
4.3 Miscellaneous String and Character Functions
4.3.1 Character Manipulation Functions
✓ Table 8.1 illustrates some character functions contained in ctype.h.
4.3.2 String Manipulation Functions
✓ The standard library ‘string.h’ contains many functions for the string manipulation.

1. strlen(str): The length of a string


✓ The ‘strlen()’ function can be used to find the length of the string in bytes.
✓ This function calculates the length of the string excluding the ‘null character’. i.e., the function returns
the number of characters in the string.
Syntax: size_t strlen(const char *str );
Ex: Write a C program to demonstrate the usage of strlen().
#include<stdio.h>
#include<string.h>
void main()
{
char str[] =“HELLO WORLD!”;
printf(“\n The length of the string is: %d”, strlen(str));
}
Output:
The length of the string is: 5

2. strcpy ( ): String Copy


✓ The ‘strcpy()’ function copies the contents of source string str2 to destination string str1 including
‘\0’.
✓ The strcpy() function copies characters from the source string to the destination string until it finds
null character. It returns the argument str1.
Syntax: char * strcpy(char *str1, const char *str2);
Where,
str1: it is the destination string
str2: it is the source string.
Ex: Write a C program to demonstrate the usage of strcpy().
#include<stdio.h>
#include<string.h>

void main()

{
char str1[10], str2[10]= “JAIN”;
strcpy(str1,str2);
printf(“The Source String=%s\n The Destination String=%s”, str1,str2);
}
Output:
The Source String= JAIN
The Destination String= JAIN

3. strcat(str1,str2): String Concatenate(Joining two strings together)


✓ The strcat function appends the string pointed to by str2 to the end of the string pointed to by str1.
✓ The ‘strcat()’ function is used to concatenate or join the two strings.
✓ The ‘strcat()’ function copies all the characters of string str2 to the end of string str1.
✓ The NULL character of string str1 is replaced by the first character of str2.
Syntax: char *strcat(char *str1, const char *str2);
Where,
str1: It is the first string
str2: It is the second string
Ex: Write a C program to demonstrate the usage of strcat().
#include<stdio.h>
#include<string.h>
void main()
{
char str1[15]= “Good”;
char str2[15]= “Morning”;
strcat(str1,str2);
printf(“The concatenated String=%s”,str1);
}

Output:
The concatenated String=GoodMorning.

4. strcmp(str1,str2): String Compare


✓ This function is used to compare two strings.
✓ The comparison starts with first character of each string. The comparison continues till the
corresponding characters differ or until the end of the character is reached.
✓ The following values are returned after comparison:
1. If two strings are equal, the function returns 0.
2. If str1 is greater than str2, a positive value is returned.
3. If str1 is less than str2, then the function returns a negative value.

Syntax: int strcmp(const char *str1, const char *str2);


Where,
str1: It is the first string.
str2: It is the second string.

Ex:
✓ “car” and “cat” are different strings. The characters ‘r’ and ‘t’ have different ASCII values. It returns
negative value since ASCII value of ‘r’ is less than the ASCII value of ‘t’.

✓ “car” and “car” are same, the function returns 0.

✓ “cat” and “car” are different strings. The characters ‘t’ and ‘r’ have different ASCII values. It returns
positive value since ASCII value of ‘t’ is greater than the ASCII value of ‘r’.
Ex: Write a C program to demonstrate the usage of strcmp().
#include<stdio.h>
#include<string.h>
void main()
{
char str1[10]=”Hello”;
char str2[10]=”Hey”;
if(strcmp(str1,str2)==0)
printf(“The two strings are identical”);
else
printf(“The two strings are not identical”);
}
Output:
The two strings are not identical

5. strrev(str): String reverse

#include <stdio.h>
#include <string.h>
int main()
{
char str[50] = "information";
printf("The given string is =%s\n", str);
printf("After reversing string is =%s", strrev(str));
return 0;
}
4.4 Arrays of Strings
✓ An array of strings is declared as
<data_type> <array_name> [row_size][column_size];
Here, the first index row_size will specify how many strings are needed and the second index
column_size will specify the length of every individual string.
Ex: char names[20][30];
✓ So here, we will allocate space for 20 names where each name can be a maximum 30 characters long.
✓ Let us see the memory representation of an array of strings. If we have an array declared as char
name[5][10] = {"Ram", "Mohan", "Shyam", "Hari", "Gopal"};
Then in the memory, the array will be stored as shown in Fig. 4.13.

✓ By declaring the array names, we allocate 50 bytes. But the actual memory occupied is 27 bytes.
Thus, we see that about half of the memory allocated is wasted.
✓ Figure 4.14 shows an algorithm to process individual string from an array of strings. In Step 1, we
initialize the index variable I to zero. In Step 2, a while loop is executed until all the strings in the
array are accessed. In Step 3, each individual string is processed.

Ex: Write a C Program to Read and Print the Names of N Students of a Class.
#include<stdio.h>
void main()
{
char names[5][10];
int i, n;
printf(“\n Enter the number of students : “);
scanf(“%d”, &n);
printf(“\n Enter the names of students :”);
for(i=0;i<n;i++)
{
scanf(“%s”,names[i]);
}
printf(“\n Names of the students are : \n”);
for(i=0;i<n;i++)
puts(names[i]);
}

[TYPE HERE] [TYPE HERE] [TYPE HERE]


Pointers
4.6 Introduction
✓ “A pointer is a variable that holds the address of another variable”. or
✓ A pointer is a variable that contains the memory location of another variable. Therefore, a
pointer is a variable that represents the location of a data item, such as a variable or an array
element.

Some of the advantages of using pointers are as follows


1. Pointers are more efficient in handling arrays and data tables
2. Pointers are used with function to return multiple values
3. Pointers allow C to support dynamic memory management
4. Pointers provide an efficient tool for manipulating dynamic data structures such as
structures, linked list, stacks, queues, trees etc
5. Pointers reduce length and complexity of program
6. Pointers reduce program execution time and saves data storage space in memory

Disadvantages of pointers
One of the disadvantage of using pointer is that program may crash if sufficient memory is not
available at run time to store pointers.
Applications of pointer
• Arrays and Strings:
Pointers can be used to traverse and manipulate arrays and strings more efficiently.
• Function Pointers:
Pointers to functions allow you to create arrays of functions, pass functions as
arguments to other functions, or return functions from functions.
• Structures:
Pointers can be used to work with structures more efficiently, especially when dealing
with large structures.
• File Handling:
Pointers are used in file handling operations, enabling efficient reading and writing of
data to files.
• Efficient Parameter Passing:
Passing pointers to functions instead of passing large data structures can be more
efficient in terms of both time and space.
• Dynamic Data Structures:
Pointers are crucial in implementing dynamic data structures such as trees and
graphs.
• Callback Functions:
Pointers to functions are often used for implementing callback mechanisms, where a
function can be passed as an argument to another function.
4.7 Declaring Pointer Variables
✓ Pointer provides access to a variable by using the address of that variable.
✓ A pointer variable is therefore a variable that stores the address of another variable.
✓ The general syntax of declaring pointer variables can be given as below.
data_type *ptr_name;
Here, data_type: is the data type of the value that the pointer will point to. It can be int, float, char etc.
Asterisk (*): It tells the compiler that we are declaring a pointer variable.
pointer_variable_name: It is the name of the pointer variable.

Example:
1. int *ptr; // declares a pointer variable ptr of integer type.
2. float *temp; // declares a pointer variable temp of floating type.

Operators used with Pointers:


The two basic operators used with pointers are:
i. The Address of operator (&): By using the address of (&) operator, we can determine the address of the
variable.
ii. The Indirection operator (*): It gives the value stored at a particular address.

Example:
int a=3;
int *ptr;
ptr=&a;
ptr a
Memory layout:
65530 3
Address: 65530
✓ ‘ptr = &a’ copies the address of ‘a’ to the pointer variable ‘ptr’.

Example Program: Write a C program to print value and address of the variable using pointers.
#include<stdio.h> Output:
void main () The address of a=65530 and value of a=20
{
int a=20, *ptr;
ptr = &a; //ptr1 is a pointer to variable a
printf(“The address of a=%d and value of a=%d\n”,ptr,*ptr);
}
ptr1 a
Memory layout:
65530 20
Address: 65530

Initializing a Pointer Variable


✓ We can initialize the pointer variables by assigning the address of other variable to them. However these
variables must be declared in the program.

Syntax
data_type * ptr_name = address_of_variable;
where,
data_type:.It can be int, float, char etc.
Asterisk (*): It tells the compiler that we are declaring a pointer variable.
ptr_name: It is the name of the pointer variable.
address_of_variable: Itis the address of another variable.
Example:
int a;
int *ptr;
ptr=&a;
or
int a;
int *ptr=&a;
Both are equivalent.

✓ We can dereference a pointer, i.e., refer to the value of the variable to which it points, by using unary
'*' operator (also known as indirection operator) as *pnum, i.e., *pnum = 10, since 10 is value of x.
Therefore, * is equivalent to writing value at address. Look at the code below which shows the use of
pointer variable.
#include <stdio.h>
void main()
{
int num, *pnum;
pnum = &num;
printf(“Enter the number : ");
scanf("%d", &num);
printf("\n The number that was entered is : %d", *pnum);
}
Output:
Enter the number : 10
The number that was entered is : 10
What will be the value of *(&num)? It is equivalent to simply writing num.

4.8 Types of Pointer


4.8.1 Null Pointers
✓ We have studied that a pointer variable is a pointer to a variable of some data type.
✓ However, in some cases, we may prefer to have a null pointer which is a special pointer value and 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, you can write
int *ptr = NULL;
✓ You can always check whether a given pointer variable stores the address of some variable or contains
NULL by writing,
if (ptr == NULL)
{
Statement block;
}
✓ You may also initialize a pointer as a null pointer by using the constant 0
int *ptr, ptr = 0;
✓ This is a valid statement in C as NULL is a preprocessor macro, which typically has the value or
replacement text 0. However, to avoid ambiguity, it is always better to use NULL to declare a null pointer.
A function that returns pointer values can return a null pointer when it is unable to perform its task.
✓ Null pointers are used in situations where one of the pointers in the program points to different
locations at different times.

4.8.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 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 cast a void 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,
#include <stdio.h>
void main()
{
int x=10;
char ch = ‘A’;
void *gp;
gp = &x;
printf("\n Generic pointer points to the integer value = %d", *(int*)gp);
gp = &ch;
printf("\n Generic pointer now points to the character= %c", *(char*)gp);
}

Output:
Generic pointer points to the integer value = 10
Generic pointer now points to the character = A

4.9 Passing Arguments to Function Using Pointers


✓ Using call-by-value method, it is impossible to modify the actual parameters when you pass them to a
function. Furthermore, the incoming arguments to a function are treated as local variables in the function
and those local variables get a copy of the values passed from their calling function.
✓ Pointer provides a mechanism to modify data declared in one function using code written in another
function. In other words: If data is declared in func1() and we write code in func2() that modifies the data
in func1(), then we must pass the addresses of the variables to func2().
✓ The calling function sends the addresses of the variables and the called function declares those
incoming arguments as pointers. In order to modify the variables sent by the calling function, the called
function must dereference the pointers that were passed to it. Thus, passing pointers to a function avoids
the overhead of copying data from one function to another.
✓ Hence, to use pointers for passing arguments to a function, the programmer must do the following:
• Declare the function parameters as pointers.
• Use the referenced pointers in the function body.
• Pass the addresses as the actual argument when the function is called.

1. Write a C program to add two numbers using call by reference.


#include<stdio.h>

int add (int *a,int *b)


{
int sum;
sum = *a + *b;
return sum;
}

void main()
{
Output:
int a,b, res;
printf(“Enter the values of a and b:”); Enter the values of a and b: 4 5
scanf(“%d%d”,&a,&b); result =9
res = add(&a,&b);
printf(“result =%d\n”, res);
}
2. Write a C program to swap two numbers using call by reference.
#include<stdio.h>
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void main()
{
int a,b;
printf(“Enter the values of a and b:”); Enter the values of a and b: 10 20
scanf(“%d%d”,&a,&b); Before swapping: a=10 b=20
printf(“Before swapping: a=%d\tb=%d”, a, b); After swapping: a=20 b=10
swap(&a,&b);
printf(“After swapping: a=%d\tb=%d”, a, b)
}

Output:
Enter the values of a and b: 10 20
Before swapping: a=10 b=20
After swapping: a=20 b=10

You might also like