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

Module-4

This document is a module on Strings and Pointers in C programming, detailing how strings are represented as null-terminated character arrays and the importance of memory allocation for strings. It explains various methods for reading and writing strings, including the use of functions like scanf, gets, printf, and puts, as well as the concept of fixed-length and variable-length strings. Additionally, it covers operations on strings and the significance of delimiters in string manipulation.

Uploaded by

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

Module-4

This document is a module on Strings and Pointers in C programming, detailing how strings are represented as null-terminated character arrays and the importance of memory allocation for strings. It explains various methods for reading and writing strings, including the use of functions like scanf, gets, printf, and puts, as well as the concept of fixed-length and variable-length strings. Additionally, it covers operations on strings and the significance of delimiters in string manipulation.

Uploaded by

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

1

Dr. H N National College of Engineering, Bengaluru


Department of Artificial Intelligence and Data Science
Principles of Programming Using C
Module-4
By,
Dr. Vikhyath K B

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Module-4 Strings and Pointers
2

• In C language, 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.

char str[] = “HELLO”;

• Declaring a character array that has five usable characters namely, H, E, L, L, O.


Apart from these characters, a null character (‘\0’) is stored at the end of the string.

• To store a string of length 5, we need 5+1 locations (1 extra for the null character).

• If we declare str as char str[5] = “HELLO”;

• Then the null character will not be appended automatically to character array. This
is because str can hold only 5 characters and the characters in HELLO have already
filled the locations allocated to it.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


3

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


4

• When the compiler assigns a character string to a character array, it automatically


appends a null character to the end of the string. Therefore, the size of the string
should be equal to maximum number of characters in the string plus one.

• When allocating memory space for a character array, reserve space to hold the null
character also.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


5

• In the above figure 1000, 1001, 1002, and so on are the memory addresses of
individual characters. As in the figure H is stored at memory location 1000 but in
reality the ASCII codes of characters are stored in memory and not the character
itself, i.e., at the address 72 will be stored since the ASCII code for H is 72.

• char str[] = “HELLO”;

• The given statement declares a constant string as we have assigned value to it while
declaring the string.

• The general form of declaring a string is: char str[size];

• When we declare the string in this way, we can store size-1 characters in the array
because the last character would be the null character.

• char str[] = { ‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’};

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


6

• In the above example, we have explicitly added the null character. Further, observe
that we have not mentioned the size of the string. Here, the compiler will
automatically calculate the size based on the number of elements initialized. So, in
this example 6 memory slots will be reserved to store the string variable, str.

• We can also declare a string with size much larger than the number of elements that
are initialized.

• char str[10] = “HELLO”;

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


7

char str[3];
str = “HELLO”;

• The above declaration is illegal in C and would generate a compile time error
because of two reasons. First, the array is initialized with more elements than it can
store. Second initialization cannot be separated from declaration.

• An array name cannot be used as the left operand of an assignment operator. The
following statement is illegal in C:

char str2, str1[] = “HI”;


str2 = str1;

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.1.1 Reading String
8

• If we declare a string by writing: char str[100];

• Then str can be read by using three ways:

1. Using scanf function


2. Using gets() function
3. Using getchar(), getch() or getche() function repeatedly.

• String can be read using scanf() by writing: scanf(“%s”, str);

• The main pitfall with this function is that the function terminates as soon as it finds
a blank space.

• Example: If the user enters Hello World then str will contain only Hello. This is
because the moment a blank space is encountered, the string is terminated by the
scanf() function. Unlike int(%d), float(%f), and char(%c), %s format does not
require ampersand before the variable name.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
9

• gets() function: Another method to read a string. gets(str);

• gets() is a simple function that overcomes the drawbacks of the scanf() function.
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.
¨ getchar() function: Another method to read a string by calling the getchar()
function repeatedly to read a sequence of single characters and simultaneously
storing it in a character array.

i=0;
ch = getchar();
while(ch !=‘*’)
{
str[i] = ch; // Store the read character in str
i++;
ch = getchar(); //Get another character
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
Str[i] = ‘\0’; // Terminate str with null character
13.1.2 Writing Strings
10

Strings can be displayed on screen using three ways:

1. Using printf() function.


2. Using puts() function.
3. Using putchar() function repeatedly.

A string can be displayed using printf() by writing:

printf(“%s”, str);

Example: printf(“%5.3s”, str);

The above statement would print only the first three characters in a total field of five
characters. Also these three characters are right justified in the allocated width. To
make the string left justified, we must use a minus sign.

printf(“%-5.3s”,str);
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
11

puts() function: The another method of writing a string is by using puts() function.
The string can be displayed by writing:

puts(str);

The puts() function writes a line of output on the screen. It terminates the line with a
new line character (‘\n’).

putchar() function: Another method used to print a sequence of single characters.

i=0;
while(str[i]!=‘\0’)
{
putchar(str[i]); // Print the character on the screen
i++;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to display a string
using printf().
12

#include <stdio.h>
int main()
{ Output:
char str[] = "Introduction to C"; |Introduction to C|
printf("\n |%s|", str);
printf("\n |%20s|", str); | Introduction to C|
printf("\n |%-20s|", str);
printf("\n |%.4s|", str); |Introduction to C |
printf("\n |%20.4s|", str);
printf("\n |%-20.4s|", str); |Intr|
return 0;
} | Intr|

|Intr |

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13

sprintf() function: The library function sprintf() is similar to printf(). The only
difference is that the formatted output is written to a memory area rather than directly
to a standard output (screen).

• sprintf() is useful in situations when formatted strings in memory have to be


transmitted over a communication channel or to a special device.

The syntax:

• int sprintf(char * buffer, const char * format [ , argument , …]);

• Here buffer is the place where the string needs to be stored. The arguments
command is an ellipsis so you can put as many types of arguments as you want.
Finally, format is the string that contains the text to be printed.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


14

#include<stdio.h>
int main()
{
char buf[100];
int num=10;
sprintf(buf, “num = %3d”, num);
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.2 Suppressing Input
15

• The scanf() function can be used to read a field without assigning it to any variable.
This is done by preceding that field’s format code with a *.

scanf(“%d*c%d”, &hr, &min);

• The time can be read as 9:05. Here the colon would be read but not assigned to
anything. Therefore, assignment suppression is particularly useful when part of
what is input needs to be suppressed.

• 13.2.1 Using a Scanset: The ANSI standard added the new scanset feature to the
C language. Scanset is used to define a set of characters which may be read and
assigned to the corresponding string. Scanset is defined by placing the characters
inside square brackets prefixed with a %, as shown in the example below.

%[“aeiou”]

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


16

• When we use the above scanset, scanf() will continue to read characters and put
them into the string until it encounters a character that is not specified in the
scanset.

#include <stdio.h>
int main()
{
char str[10];
printf("\n Enter string:");
scanf("%[aeiou]",str);
printf("The string is:", str);
return 0;
}

• The code will stop accepting a character as soon as the user enters a character that
is not vowel.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


17

• However, if the first character in the set is a ^ (caret symbol), then scanf() will
accept any character that is not defined by the scanset.

scnaf(“%[^aeiou]”,str);

• Then, str will accept character other than those specified in the scanset, i.e., it will
accept any non-vowel character.

• The user can also specify a range of acceptable characters using a hyphen. This is
shown in the statement given below:

scanf(“%[a-z]”,str);

• Here, str will accept any character from small a to small z. Always remember that
scanset are case sensitive.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


18

#include <stdio.h>

int main()
{
char str[10];
printf("\n Enter string:");
scanf("%[A-Z]", str); // Reads only the upper case characters
printf(" The string is: %s", str);

return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


19

• Scanset may also terminated if a field width specification is include and the
maximum number of charactes that can be read has been reached.

scanf(“%10[aeiou]”, str);

• The above statement will read maximum 10 vowels. So the scanf statement will
terminate if 10 characters have been read or if a non-vowel character is entered.

• sscanf function: The sscanf function accepts a string from which to read
input. It accepts a template string and a series of related arguments. The sscanf
function is similar to scanf function except that the first argument of sscanf
specifies a string from which to read, whereas scanf can only read from standard
input. Its syntax in given as:

sscanf(const char *str, const char *format, [p1, p2, …..]);

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


20

• Here sscanf() reads data from str and store them according to the parameter format
into the locations given by the additional arguments.

• Locations pointed by each additional argument are filled with their corresponding
type of value specified in the format string.

sscanf(str, “%d”, &num);

• Here sscanf takes three arguments. The first is str that contains data to be
converted. The second is a string containing a format specifier that determines how
the string is converted. Finally, the third is a memory location to place the result of
the conversion. When the sscanf function completes successfully, it returns the
number of item successfully read.

• Similar to scanf(), sscanf() terminates as soon as it encounters a space, i.e., it


continues to read till it comes across a blank space.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.3 String Taxonomy
21

• In C, we can store a string either in fixed-length format or in variable-length format


as below:

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


22

Fixed-length string: When storing a string in a fixed-length format, we have to


specify an appropriate size for the string variable.

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.

To use a variable-length string format we 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: Here we 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 String: In this the string is ended with a delimiter. The delimiter is then
used to identify the end of the string.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


23

Example: In English language every sentence is ended with a full-stop (.). Similarly,
in C language we can use any character such as comma, semicolon, colon, dash, null
character, etc. as the delimiter of a string. Null character is the most commonly used
string delimiter in the C language.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.4 Operation on strings
24

Before we learn about the different operations that can be performed on character
arrays, we must understand the way arithmetic operations can be applied to characters.

int i;
char ch = ‘A’;
i = ch;
printf(“%d”, i);

// Prints 65, ASCII value of ch is ‘A’

int i;
char ch = ‘A’;
i = ch + 10;
printf(“%d”, i);

// Prints 75, ASCII value of ch that is ‘A’ + 10


Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
13.4.1 Finding the Length of a String
25

The number of characters in the string constitutes the length of the string.

Example: LENGTH (“C Programming is fun”) will return 20. Note that even blank
spaces are counted as characters in the string.

LENGTH (“\0”) =0 and LENGTH(“ “) = 0 because both the string do not contain
any character. Therefore, both the strings are empty and of zero length.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to find the length of
string
26

#include <stdio.h>
int main()
{
char str[100], i = 0, length;
printf(" \n Enter the String:");
gets(str);
while(str[i]!='\0')
i++;
length = i;
printf("\n The length of the string is: %d", length);
return 0;
}

Output:

Enter the String: HELLO


The length of the string is: 5
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
13.4.2 Converting Characters of a String
into Upper Case
27

As we already know that in memory the ASCII codes are stored instead of all real
value. The ASCII code for A-Z varies from 65-91 and ASCII code for a-z ranges from
97-123.

So, if we have to convert a lower case letter to upper case letter, then we just need to
subtract 32 from the ASCII value of the character.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to convert characters
of a string to upper case.
28

#include <stdio.h>
int main()
{
char str[100], upper_str[100];
int i = 0, j=0;
printf(" \n Enter the String:");
gets(str);
while(str[i]!='\0')
{
if(str[i]>='a' && str[i]<='z')
upper_str[j] = str[i]-32;
else
upper_str[j] = str[i];
i++;
j++;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


29

upper_str[j] = '\0';
printf("\n The string converted into upper case is:");
puts(upper_str);
return 0;
}

Output:

Enter the String: hello

The string converted into upper case is: HELLO

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.4.3 Converting Characters of a String
into Lower Case
30

If we want to convert upper case character into lower case, then we just need to add 32
to its ASCII value.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to convert character of
a string into lower case.
31

#include <stdio.h>
int main()
{
char str[100], lower_str[100];
int i = 0, j=0;
printf(" \n Enter the String:");
gets(str);
while(str[i]!='\0')
{
if(str[i]>='A' && str[i]<='Z')
lower_str[j] = str[i]+32;
else
lower_str[j] = str[i];
i++;
j++;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


32

lower_str[j] = '\0';
printf("\n The string converted into upper case is:");
puts(lower_str);
return 0;
}

Output:

Enter the String: HELLO

The string converted into upper case is: hello

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.4.4 Concatenating Two strings to
Form a New String
33

If S1 and S2 are two strings, then concatenation operation produces a string which
contains characters of S1 followed by the Characters of S2.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to concatenate two
strings.
34

#include <stdio.h>
int main()
{
char str1[100],str2[100], str3[100];
int i = 0, j=0;
printf(" \n Enter the first String:");
gets(str1);
printf(" \n Enter the second String:");
gets(str2);
while(str1[i]!='\0')
{
str3[j] = str1[i];
i++;
j++;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


35

i = 0;
while(str2[i]!='\0')
{
str3[j] = str2[i];
i++;
j++;
}
str3[j] = '\0';
printf("\n The concatenated string is:");
puts(str3);
return 0;
}

Output:
Enter the first String: HN
Enter the second String: NCE
The concatenated string is:HNNCE
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
13.4.5 Appending a String to Another
String
36

Appending one string to another string involves copying the contents of the source
string at the end of the destination string.

Example: If S1 and S2 are two strings, then appending S1 to S2 means we have to add
the contents of S1 to S2. Here S1 is the source and S2 is the destination string.

S2 = S2 + S1

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to append a string to
another string
37

#include <stdio.h>
int main()
{
char Dest_Str[100],Source_Str[50];
int i=0, j=0;
printf("\n Enter the source string:");
gets(Source_Str);
printf("\n Enter the destination string:");
gets(Dest_Str);
while(Dest_Str[i] != '\0')
i++;
while(Source_Str[j] !='\0')
{
Dest_Str[i] = Source_Str[j];
i++;
j++;
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
38

Dest_Str[i] = '\0';
printf("\n After appending, the destination string is:");
puts(Dest_Str);
return 0;
}

Output:

Enter the source string: HNNCE

Enter the destination string: Bengaluru

After appending, the destination string is: BengaluruHNNCE

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.4.6 Comparing Two Strings
39

If S1 and S2 are two strings then comparing two strings will give either of these
results.

1. S1 and S2 are equal


2. S1 > S2 when in dictionary order S1 will come after S2
3. 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 same then the two strings are said to be equal.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to compare two strings
40

#include <stdio.h>
#include<string.h>
int main()
{
char str1[50], str2[50];
int i=0, len1=0, len2=0, same=0;

printf("\n Enter the first string:");


gets(str1);
printf("\n Enter the second string:");
gets(str2);
len1 = strlen(str1);
len2 = strlen(str2);
if(len1==len2)
{

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


41

while(i<len1)
{
if(str1[i] == str2[i])
i++;
else break;
}
if(i==len1)
{
same=1;
printf("\n The two strings are equal");
}
if(len1!=len2)
printf("\n The two strings are not equal");
if(same==0)
{

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


42

if(str1[i]>str2[i])
printf("\n String1 is greater than dtring2");
else if(str1[i]<str2[i])
printf("\n String2 is greater than string1");
}
}
return 0;
}

Output:

Enter the first string: Hello


Enter the second string: Hello
The two strings are equal

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.4.7 Reversing a String
43

If S1 = “HELLO”, then reverse of S1 = “OLLEH”. To reverse a string we just need to


swap the first character with the last, second character with the second last character,
so on and so forth.

#include <stdio.h>
#include<string.h>
int main()
{
char str[100], reverse_str[100],temp;
int i=0, j=0;
printf("\n Enter the string");
gets(str);
j = strlen(str)-1;
while(i<j)
{
temp = str[j];
str[j] = str[i];
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
str[i] = temp;
44

i++;
j++;
}
printf("\n The reverse string is:");
puts(str);
return 0;
}

Output:

Enter the string: HELLO

The reverse string is: OLLEH

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.4.8 Extracting a Substring from left
45

¨ In order to extract a substring from the main string we need to copy the content of
the string starting from the first position to the nth position where n is the number
of characters to be extracted.

¨ Example: S1 = “Hello World”,


¨ Substr_Left(S1, 7) = Hello W

#include <stdio.h>
#include<string.h>

int main()
{
char str[100], substr[100];
int i=0, n;
printf("\n Enter the string:");
gets(str);
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
46

printf(" Enter the number of characters to be copied:");


scanf("%d", &n);
i = 0;
while(str[i] != '\0' && i<n )
{
substr[i] = str[i];
i++;
}
substr [i] = '\0';
printf("\n The substring is:");
puts(substr);
return 0;
}
Output: Enter the string: Hi There
Enter the number of characters to be copied: 2
The substring is: Hi
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
13.4.9 Extracting a Substring from
Right of the String
47

In order to extract a substring from the right side of the main string we need to first
calculate the position from the left. If S1 = “Hello World” and we have to copy 7
characters starting from the right, then we have to actually start extracting characters
from the 4th position. This is calculated by total number of characters – n;
Example: Substr_Right(S1, 7) = o World

#include <stdio.h>
#include<string.h>

int main()
{
char str[100], substr[100];
int i=0, j=0, n;
printf("\n Enter the string:");
gets(str);
printf(" Enter the number of characters to be copied:");
scanf("%d",&n);
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
j = strlen(str) - n;
48

while(str[j] != '\0' )
{
substr[i] = str[j];
i++;
j++;
}
substr [i] = '\0'; Output:
printf("\n The substring is:"); Enter the string: Hello World
puts(substr);
return 0; Enter the number of characters to be copied:7
}
The substring is: o World

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.4.10 Extracting a Substring from the
Middle of a String
49

¨ To extract a substring from a given string requires information about three things.
The main string, the position of the first character of the substring in the given
string, and the number of character/length of the substring.

¨ Example: str[] = “Welcome to the world of Programming”;


¨ Sub_String(str, 15, 5) = world;
#include <stdio.h>
#include<string.h>

int main()
{
char str[100], substr[100];
int i=0, j=0, n, m;
printf("\n Enter the string:");
gets(str);

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


50

printf(" Enter the position from which to start the substring:");


scanf("%d",&m);
printf("\n Enter the length of the substring:");
scanf("%d", &n);
i = m;
while(str[i] != '\0' && n>0) Output:
{ Enter the string: Hi Three
substr[j] = str[i]; Enter the position from which to start the substring:1
i++; Enter the length of the substring:7
j++; The substring is: i Three
n--;
}
substr[j]='\0';
printf("\n The substring is:");
puts(str);
return 0;
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
13.4.11 Inserting a String in Another
String
51

¨ The insertion operation inserts a string S in the main text T at Kth position. The
general syntax of this operation is: INSERT(text, position, string).
¨ Example: INSERT(“XYZXYZ”, 3, “AAA”) = XYZAAAXYZ

#include <stdio.h>
#include<string.h>
int main()
{
char text[100], str[100], ins_text[100];
int i=0, j=0, k=0, pos;
printf("\n Enter the main text:");
gets(text);
printf(" Enter the string to be inserted:");
gets(str);
printf("\n Enter the position at which the string has to be inserted:");
scanf("%d", &pos);
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
52

while(text[i]!='\0')
{
if(i==pos)
{
while(str[k]!='\0')
{
ins_text[j]=str[k];
j++;
k++;
}
}
else
{
ins_text[j]=text[i];
j++;
}
i++;
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
53

ins_text[j]='\0';
printf("\n The new string is:");
puts(ins_text);
return 0;
}

Output:

Enter the main text: How You ?


Enter the string to be inserted: Are
Enter the position at which the string has to be inserted: 3
The new string is: How Are You?

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.4.12 Indexing
54

¨ Index operation returns the position in the string where the string pattern first
occurs. However, if the pattern does not exist in the string, the INDEX function
returns 0.

¨ Example: INDEX(“Welcome to the world of programming”, world) = 15;

13.4.13 Deleting a String from the Main String

¨ The deletion operation deletes a substring from a given text.

¨ Example: DELETE(“ABCDXXXABCD”, 4, 3) = “ABCDABCD”

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to delete a substring
from a text.
55

#include <stdio.h>
#include<string.h>

int main()
{
char text[200], str[200], new_text[200];
int i=0, j=0, k, n=0, copy_loop=0;

printf("\n Enter the main text:");


gets(text);
printf(" Enter the string to be deleted:");
gets(str);
while(text[i]!='\0')
{
j=0, k=i;
while(text[k]==str[j] && str[j]!='\0')

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


56

{
k++; Output:
j++; Enter the main text: Hello, How are you
}
if(str[j]=='\0') Enter the string to be deleted:, How are you
copy_loop=k;
new_text[n] = text[copy_loop]; The new string is: Hello
i++;
copy_loop++;
n++;
}
new_text[n]= '\0';
printf("\n The new string is:");
puts(new_text);
return 0;
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
13.4.14 Replacing a Pattern with
Another Pattern in a String
57

¨ Replacement operation is used to replace the pattern P1 by another pattern P2. This
is done by writing:
REPLACE(text, pattern1, pattern2)
¨ Example 1:
(AAABBBCCC”, “BBB”, “X”) = AAAXCCC

¨ Example2:
(AAABBBCCC”, “X”, “YYY”) = AAABBBCCC

¨ In the second example, there is no change as ‘X’ does not appear in the text.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to replace a pattern
with another pattern in the text
58

#include <stdio.h>
#include<string.h>

int main()
{
char str[200], pat[200], new_str[200], rep_pat[100];
int i=0, j=0, k, n=0, copy_loop=0, rep_index = 0;
printf("\n Enter the string:");
gets(str);
printf(" Enter the pattern to be replaced:");
gets(pat);
printf(" Enter the replacing pattern:");
gets(rep_pat);

while(str[i]!='\0')
{
j=0, k=i;
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
59

while(str[k]==pat[j] && pat[j]!='\0')


{
k++;
j++;
}
if(pat[j]=='\0')
copy_loop=k;
while(rep_pat[rep_index] != '\0')
{
new_str[n] = rep_pat[rep_index];
rep_index++;
n++;
}
}
new_str[n] = str[copy_loop];
i++;
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
60

copy_loop++;
n++;
}
new_str[n] = '\0';
printf("\n The new string is:");
puts(new_str);
return 0;
}

Output:
Enter the string: How ARE you?
Enter the pattern to be replaced: ARE
Enter the replacing pattern: are
The new string is: How are you?

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.5 Miscellaneous String and Character
Functions
61

¨ Character and string manipulation functions that are part of header files ctype.h,
string.h, stdlib.h.
¨ 13.5.1 Character Manipulation Functions : Below table
illustrates some character functions contained in ctype.h

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


62

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13.5.2 String Manipulation Functions
63

strcat Function:

Syntax:
char *strcat(char *str1, const char *str2);

The strcat function appends the string pointed to by str2 to the end of the string
pointed to by str1.

The terminating null character of str1 is overwritten. The process stops when the
terminating null character of str2 is copied. The argument str1 is returned.

Note: the str1 should be big enough to store the content of str2.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


64

#include <stdio.h>
#include<string.h>
int main()
{
char str1[50] = "Programming";
char str2[] = " In C";
strcat(str1, str2);
printf("\n str1: %s", str1);
return 0;
}

Output:
str1: Programming In C

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


65

strncat Function:
Syntax:
char *strncat(char *str1, const char *str2, size_t n);
The function appends the string pointed to by str2 to the end of the string pointed to by
str1 up to n characters long.

The terminating null character of str1 is overwritten.

Copying stops when n characters are copied or the terminating null character of str2 is
copied.

A terminating null character is appended to str1 before returning to the calling


function.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


66

#include <stdio.h>
#include<string.h>
int main()
{
char str1[50] = "Programming ";
char str2[] = "In C";
strncat(str1, str2, 2);
printf("\n str1: %s", str1);
return 0;
}

Output:
str1: Programming In

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


67

strchr Function:

Syntax:
char *strchr(const char *str, int c);

The strchr() function searches for the first occurrence of the character c ( an unsinged
char) in the string pointed to by the argument str. The function returns a pointer
pointing to the first matching character, or NULL if no match is found.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


68

#include <stdio.h>
#include<string.h>
int main()
{
char str[50] = "Programming In C";
char *pos;
pos = strchr(str,'n');
if(pos)
printf("\n n is found in str at position %d", pos);
else
printf("\n n is not present in the string");
return 0;
}

Output:
n is found in str at position 9
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
69

strrchr Function:

Syntax:
char *strrchr(const char *str, int c);

The strrchr() function searches for the first occurrence of the character c(an unsinged
char) beginning at the rear end and working towards the front in the string pointed to
by the argument str, i.e., The function searches for the last occurrence of the character
C and returns a pointer pointing to the last matching character, or NULL if no match is
found.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


70

#include <stdio.h>
#include<string.h>
int main()
{
char str[50] = "Programming In C";
char *pos;
pos = strrchr(str,'n');
if(pos)
printf("\n The last position of n is: %d", pos);
else
printf("\n n is not present in the string");
return 0;
}

Output:
The last position of n is: 13

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


71

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

The strcmp function compares the string pointed to by str1 to the string pointed to by
str2. The function returns zero if the string are equal. Otherwise, it returns a value less
than zero or greater than zero if str1 is less than or greater than str2 respectively.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


72

#include <stdio.h>
#include<string.h>
int main()
{
char str1[10] = "HELLO" ;
char str2[10] = "HEY";
if(strcmp(str1,str2)==0)
printf("\n Two strings are identical");
else
printf("\n The two strings are not identical");
return 0;
}

Output:
The two strings are not identical

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


73

strncmp Function:
Syntax:

int strncmp(const char *str1, const char *str2, size_t n);

This function compares at most the first n bytes of str1 and str2. The process stops
comparing after the null character is encountered. The function returns zero if the first
n bytes of the string are equal. Otherwise, it returns a value less than zero or greater
than zero if str1 is less than or greater than str2, respectively.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


74

#include <stdio.h>
#include<string.h>
int main()
{
char str1[10] = "HELLO" ;
char str2[10] = "HEY";
if(strncmp(str1,str2,2)==0)
printf("\n Two strings are identical");
else
printf("\n The two strings are not identical");
return 0;
}

Output:
Two strings are identical

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


75

strcpy Function:

Syntax: char *strcpy(char *str1, const char *str2);

This function copies the string pointed to by str2 to str1 including the null character of
str2. It returns the argument str1. Here str1 should be big enough to store the contents
of str2.

#include <stdio.h> Output:


#include<string.h> str1: HELLO
int main()
{
char str1[10], str2[10] = "HELLO" ;
strcpy(str1,str2);
printf("\n str1: %s", str1);
return 0;
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
76

strncpy Function:

Syntax: char *strncpy(char *str1, const char *str2, size_t n);

This function copies up to n characters from the string pointed to by str2 to str1.
Copying stops when n characters are copied. However, if the null character in str2 is
reached then the null character is continually copied to str1 until n characters have
been copied. Finally, a null character is appended to str1. However, if n is zero or
negative then nothing is copied.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


77

#include <stdio.h>
#include<string.h>
int main()
{
char str1[10], str2[10] = "HELLO" ;
strncpy(str1,str2,2);
printf("\n str1: %s", str1);
return 0;
}

Output:
str1: HE

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


78

strlen Function:
Synatx: size_t strlen(const char *str);

This function calculates the length of the string str up to but not including the null
character, i.e., the function returns the number of characters in the string.
#include <stdio.h>
#include<string.h>
int main()
{
char str[] = "HELLO" ;
printf("\n Length of str is: %d", strlen(str));
return 0;
}

Output: Length of str is: 5


Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
79

strstr Function:
Syntax: char *strstr(const char *str1, const char *str2);

This function is used to find the first occurrence of string str2 in the string str1. It
returns a pointer to the first occurrence of str2 in str1. If no match is found, then a null
pointer is returned.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


80

#include <stdio.h>
#include<string.h>
int main()
{
char str1[] = "HAPPY BIRTHDAY TO YOU" ;
char str2[] = "DAY";
char *ptr;
ptr = strstr(str1, str2);
if(ptr)
printf("\n Substring Found");
else
printf("\n Substring Not Found");
return 0;
}

Output: Substring Found

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


81

strspn Function:
Syntax: size_t strspn(const char *str1, const char *str2);
The function returns the index of the first character in str1 that doesn’t match any
character in str2.

#include <stdio.h>
#include<string.h>
int main()
{
char str1[]="HAPPY BIRTHDAY TO YOU";
char str2[]="HAPPY BIRTHDAY JOE";
printf("\n The position of first character in str2 that does not match with that in str1 is
%d",strspn(str1,str2));
return 0;
}
Output: The position of first character in str2 that does not match with that in str1 is
15 Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
82

strcspn Function:
Syntax: size_t strcspn(const char *str1, const char *str2);
The function returns the index of the first character in str1 that matches any of the
character in str2.
#include <stdio.h>
#include<string.h>
int main()
{
char str1[]="PROGRAMMIN IN C";
char str2[]="IN";
printf("\n The position of first character in str2 that matches with that in str1 is
%d",strspn(str1,str2));
return 0;
}
Output: The position of first character in str2 that matches with that in str1 is 8

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


83

strpbrk Function:
Syntax: char *strpbrk(const char *str1, const char *str2);

The function strpbrk() returns a pointer to the first occurrence in str1 of any character
in str2, or NULL if none are present. The only difference between strpbrk() and
strcspn is that strcspn() returns the index of the character and strpbrk() returns a
pointer to the first occurrence of a character in str2.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


84

#include <stdio.h>
#include<string.h>
int main()
{
char str1[]="PROGRAMMIN IN C";
char str2[]="AB";
char *ptr=strpbrk(str1,str2);
if(ptr==NULL)
printf("\n No character matches in the two strings");
else
printf("\n. Character in str2 matches with that in str1");
return 0;
}
Output: No character matches in the two strings

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


85

strtok Function:
Syntax: char *strtok(char *str1, const char *delimeter);

The strtok() function is used to isolate sequential token in a null-terminated string, str.
These tokens are separated in the string delimiters. The first time that strtok is called,
str should be specified; subsequent calls, wishing to obtain further tokens from the
same string, should pass a null pointer instead. However, the delimiter must be
supplied each time, though it may change between calls.

The strtok() function returns a pointer to the beginning of each subsequent token in the
string, after replacing the token itself with a null character. When all tokens are left, a
null pointer is returned.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


86

#include <stdio.h>
#include<string.h>
int main()
{
char str[] = " Hello, to, the, world of, programming";
char delim[]=” , ";
char result[20];
result = strtok(str,delim); Output:
while(result!=NULL) Hello
{ to
printf("\n %s", result); the
result=strtok(NULL,delim); world of
} programming
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


87

strtol Function:
syntax: long strtol(const char *str, char **end, int base);

The strtol function converts the string pointed by str to a long value. The function
skips leading white space characters and stops when it encounters the first non-
numeric character. Strlok stores the address of the first invalid character in str in *end.
If there were no digits at all, then the strtol function will store the original value of str
in *end. We may pass NULL instead of *end if you do not want to store the invalid
characters anywhere.

Finally, the third argument base specifies whether the number is in hexadecimal, octal,
binary, or decimal representation.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


88

#include <stdio.h>
#include<string.h>
int main()
Output:
{
12345
long num;
27418
num=strtol("12345 Decimal Value", NULL, 10);
181
printf("\n %ld",num);
687284
num=strtol("65432 Octal Value", NULL, 8);
printf("\n%ld", num);
num = strtol("10110101 Binary value", NULL,2);
printf("\n%ld",num);
num=strtol("A7CB4 Hexadecimal Value", Null,16);
printf("\n%ld",num);
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


89

Strtod Function:
Syntax: double strtod(const char *str, char **end);

The function accepts a string str that has an optional plus (‘+’) or minus sign(‘-’)
followed by either:
A decimal number containing a sequence of decimal digits optionally consisting of a
decimal point or

A hexadecimal number consisting of a ”OX” or “Ox” followed by a sequence of


hexadecimal digits optionally containing a decimal point.

In both cases , the number may be optionally followed by an exponent (‘E’ or ‘e’ for
decimal constants or a ‘P’ or ’p’ for hexadecimal constants), followed by an optional
plus or minus sign, followed by a sequence od decimal digits.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
90

#include <stdio.h>
#include<stdlib.h>
int main()
{
double num;
num = strtod("123.345abcdef",NULL);
printf("%lf", num);
return 0;
}

Output:

123.345000

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


91

atoi() Function:
As we know that the value 1 is an integer and ‘1’ is a character. So there is a huge
difference when we write the two statements given below.

int i=1; // here i=1


int i=‘1’; // here i = 49, the ASCII value of character 1

Similarly, 123 is an integer number but ‘123’ is a string of digits. What if you want to
operate some integer operations on the string ‘123’? For this, C provides a function
atoi that converts a given string into its corresponding integer.

int atoi (const char *str);


Example: i=atoi(“123.456”);
Result: i = 123.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
92

atof() Function:

The atof() function converts the string that it accepts as an argument into a double
value and then returns that value to the calling function.

Syntax:
double atof(const char *str);

Example: x = atof(“12.39 is the answer”);


Result: x = 12.39

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


93

atol() Function:

The atol() function converts the string into a long int value. The atol function returns
the converted long value to the calling function. Like atoi, the atlo() function will read
from a string until it finds any character that should not be in a long.

Syntax: long atoll(const char *str);

Example: x=atol(“12345.6789”);
Result: x=12345L.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


13. 6 Arrays of Strings
94

¨ If there are 20 students in a class and we need a string that stores names of all the
20 students.

¨ Here, we need a string of strings or an array of strings. Such an array of strings


would store 20 individual strings. An array of strings is declared as:

char names[20][30];

¨ Here, the first index that specifies the number of strings that are needed and the
second index specifies the length of every individual string. So here, we allocate
space for 20 names where each name can be a maximum of 30 characters long.

<data_type> <array_name> = { “Ram”, “Mohan”, “Shyam”, “Hari”, “Gopal”};

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


95

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to read and print the
names of n students of a class
96

#include <stdio.h>
int main()
{
char names[5][10];
int i,n;
printf("\n Enter the number of students:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter the name of student %d:", i+1);
gets(names[i]);
}
printf("\n Names of the student are: \n");
for(i=0;i<n;i++)
puts(names[i]);
return 0;
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
97

Output:
¨ Enter the number of students: 2
¨ Enter the name of student 1: ABC
¨ Enter the name of student 2: XYZ
¨ Names of student are: ABC XYZ

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


14. Pointers
98

14.1 Understanding the Computer’s Memory


¨ Every computer has a primary memory. All data and programs need to be placed in
the primary memory for the execution.

¨ RAM is a part of the primary memory, is a collection of memory locations and


each location has a specific address.

¨ Each memory location is capable of storing 1byte of data.

¨ Ex: char type data needs just 1 memory location and int type data needs 2 memory
locations.

¨ In general, the computer has three areas of memory each of which is used for a
specific task. These areas of memory includes : stack, heap, and global memory.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


99

¨ Stack: A fixed size of memory called system stack is allocated by the system and is
filled as needed from the bottom to the top, one element at a time.

¨ These elements can be removed from the top to the bottom by removing one
element at a time, i.e., the last element added to the stack is removed first.

¨ Heap: It is a contiguous block of memory that is available for use by programs


when the need arises. A fixed size heap is allocated by the system and is used by
the system in a random fashion.

¨ The addresses of the memory locations in heap that are not currently allocated to
any program for use are stored in a free list. When a program requests a block of
memory the dynamic allocation technique takes a block from the heap and assigns
it to the program. When the program has finished using the block, it returns the
memory block to the heap and the addresses of the memory locations in that block
are added to the free list.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
¨
100

¨ Global Memory: The block of code that is the main() program is stored in the
global memory.

¨ The memory in the global area is allocated randomly to store the code of different
functions in the program in such a way that one function is not contiguous to
another function.

¨ Beside the function code, all global variables declared in the program are stored in
the global memory area.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


14.2 Introduction to Pointers
101

¨ Every variable in C has a name and a value associated with it. When a variable is
declared, a specific block of memory within the computer is allocated to hold the
value of that variable.

¨ The size of the allocated block depends on the type of the data.

¨ The size of integer may vary from one system to another. In 32 bit systems, integer
variable is allocated 4 bytes while on 16 bit systems it is allocated 2 bytes.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to find the size of
various data types on your system.
102

#include<stdio.h>
int main()
{
printf("\n The size of short integer is:%d", sizeof(short int));
printf("\n The size of unsigned integer is %d", sizeof(unsigned int));
printf("\n The size of signed integer is %d", sizeof(signed int));
printf("\n The size of integer is %d", sizeof(int));
printf("\n The size of long integer is %d", sizeof(long int));
printf("\n The size of character is %d", sizeof(char));
printf("\n The size of unsigned character is %d", sizeof(unsigned char));
printf("\n The size of signed charactet is %d", sizeof(signed char));
printf("\n The size of floating point number is %d", sizeof(float));
printf("\n The size of idouble is %d", sizeof(double));
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


103

Output:
¨ The size of short integer is:2
¨ The size of unsigned integer is 4
¨ The size of signed integer is 4
¨ The size of integer is 4
¨ The size of long integer is 8
¨ The size of character is 1
¨ The size of unsigned character is 1
¨ The size of signed character is 1
¨ The size of floating point number is 4
¨ The size of double is 8

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


104

¨ Pointer: Is nothing but memory addresses. 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 any array element.

Applications:
¨ To pass information back and forth between a function and its reference point.
¨ Enable programmers to return multiple data items from a function via function
arguments.
¨ Provide an alternate way to access individual elements of the array.
¨ To pass arrays and strings as function arguments.
¨ Enable references to functions. So with pointers, programmers can even pass
function as argument to another function.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
105

¨ To create complex data structures such as tress, linked lists, linked stacks, linked
queues, and graphs.

¨ For dynamic memory allocation of a variable.

14.3 Declaring Pointer Variables: A 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.

Syntax of declaring pointer variable: data_type *ptr_name;

Here, data_type is the data type of the value that the pointer will point to.

int *pnum;
char *pch;
float *pfnum;
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
106

#include<stdio.h>
int main()
{
int *pnum;
char *pch;
float *pfnum;
double *pdnum;
long *plnum;
printf("\n Size of integer pointer = %d", sizeof(pnum));
printf("\n Size of character pointer = %d", sizeof(pch));
printf("\n Size of float pointer = %d", sizeof(pfnum));
printf("\n Size of double pointer = %d", sizeof(pdnum));
printf("\n Size of long pointer = %d", sizeof(plnum));
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


107

¨ Declare an integer pointer variable and start using it in the program.

¨ int x =10;
¨ int *ptr;
¨ ptr = &x;

¨ In the above ptr is the name of pointer variable. The ‘*’ informs the compiler that
ptr is a pointer variable and the int specifies that it will store the address of an
integer variable.

¨ An integer pointer variable, therefore, points to an integer variable. Here ptr is


assigned the address of x. The & operator retrieves the lvalue (address) of x, and
assigns it to the pointer ptr.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


108

¨ Since X is an integer variable, it will be allocated 2 bytes. Assuming that the


compiler assigns it memory locations 1003 and 1004, we say the value of x = 10
and the address of x (written as &x) is equal to 1003, i.e., the starting address of x
in the memory.

¨ We write, ptr = &x, the ptr = 1003

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


109

¨ 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 *ptr, i.e.,
*ptr = 10, since 10 is value of x. Therefore, * is equivalent to writing value at
address.

#include<stdio.h> Output:
int main() ¨ Enter the number10
{
int num, *pnum; ¨ The number that was entered is: 10
pnum = &num; ¨ The address of number in memory is:
0x7fff9f61bd44
printf("\n Enter the number");
scanf("%d", &num);
printf("\n The number that was entered is: %d", *pnum);
printf("\n The address of number in memory is: %p", &num);
return 0;
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
110

¨ Note: what will be the value of *(&num) ? Yes it is equivalent to num. The
indirection and the address operators are inverse of each other, so when combined
in an expression, they cancel each other.
¨ We can also assign values to variables using pointer variables and modify their
values.
#include<stdio.h>
Output:
int main()
{ ¨ *pnum = 10

int num, *pnum; ¨ num = 10


pnum = &num;
¨ After increment *pnum =11
*pnum = 10;
printf("\n *pnum = %d", *pnum); ¨ After increment num = 11
printf("\n num = %d", num);
*pnum = *pnum + 1;
printf("\n After increment *pnum =%d", *pnum);
printf("\n After increment num = %d", num);
return 0;
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
}
14.5 Null Pointer
111

¨ Pointer variable is a pointer to some other variable of the same data type. However
in some special cases we may prefer to have null pointer which is a special pointer
that does not point to any value.

¨ 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 header files in the program: int *ptr = NULL;
¨ We may also initialize a pointer as a null pointer by using a constant 0, as below:

if(ptr == NULL)
{
Statement Block;
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
}
112

¨ We can also initialize a pointer as a null pointer by using a constant 0 as shown


below:

¨ int ptr;
¨ ptr = 0;

¨ This is a valid statement in C, as NULL which is a preprocessor macro 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 situation where one of the pointer in the program points to
different locations at different times.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
14.6 Generic Pointer
113

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

¨ void *ptr;

¨ In C, since we cannot have a variable of type void, the void pointer will therefore
not point to any data and thus cannot be dereferenced.

¨ We need to type cast a void pointer (generic pointer) to another kind of pointer
before using it.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
114

¨ Generic pointer are often used when we want a pointer to point to data of different
types at different times.
#include<stdio.h>
int 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 charcater = %c", *(char*)gp);
return 0;
}
Output:
Generic pointer points to the integer value = 10
Generic pointer now points to the character = A
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
14.7 Passing Arguments to function
using Pointers
115

¨ Call-by-value: passing parameters to a function. In this approach it is impossible to


modify the actual parameters when we pass them to a function.

¨ The incoming arguments to a functions are treated as local variables in the function
and those local variables get a copy of the values passed from their calling
function.

¨ Pointers provides a mechanism to modify data declared in one function using code
written in another function.

¨ If data is declared in func1() and we want to write code in func2() that modifies the
data in func1(), then we must pass the address of the variables to func2().

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


116

¨ 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 dereferenced pointers in the function body
¨ Pass the addresses as the actual argument when the function is called.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25


Write a program to add two integers
using functions
117

#include<stdio.h>
void sum(int *a, int *b, int *t); Output:
int main() ¨ Enter the first number: 2
{
¨ Enter the second number: 3
int num1, num2, total;
printf("\n Enter the first number:"); ¨ Total = 5

scanf("%d", &num1);
printf("\n Enter the second number:");
scanf("%d", &num2);
sum(&num1, &num2, &total);
printf("\n Total = %d", total);
return 0;
}
void sum(int *a, int *b, int *t)
{
*t = *a + *b;
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25
118 Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 06/01/25

You might also like