Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
568 views

Bpops103 M 4 Strings N Pointers - Notes

The document provides information on strings and pointers in C programming. It discusses strings as arrays of characters terminated by a null character. It describes declaring and initializing string variables, as well as reading and writing strings using functions like scanf(), gets(), printf(), and puts(). The document also covers string operations like finding the length of a string and converting characters to uppercase. Pointers are introduced as variables that store memory addresses.

Uploaded by

kourpreetika
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
568 views

Bpops103 M 4 Strings N Pointers - Notes

The document provides information on strings and pointers in C programming. It discusses strings as arrays of characters terminated by a null character. It describes declaring and initializing string variables, as well as reading and writing strings using functions like scanf(), gets(), printf(), and puts(). The document also covers string operations like finding the length of a string and converting characters to uppercase. Pointers are introduced as variables that store memory addresses.

Uploaded by

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

BPOPS103-Principles of

Programming using C
MODULE-4 Notes

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.

Dr. SANTOSH K C

Associate Professor

Dept. of CSE

B. I. E. T., Davangere
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.

B.I.E.T. Davangere 1
✓ 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
B.I.E.T. Davangere 2
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.

B.I.E.T. Davangere 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.

B.I.E.T. Davangere 4
2. Converting Characters of a String into Upper Case
✓ We have already discussed that in the memory ASCII codes are stored instead of the real values. The
ASCII code for A–Z varies from 65 to 91 and the ASCII code for a–z ranges from 97 to 123. So,
if we have to convert a lower case character into uppercase, we just need to subtract 32 from the
ASCII value of the character.
✓ Figure 4.4 shows an algorithm that converts the lower case characters of a string into upper case. In
the algorithm, we initialize I to zero. Using I as the index of STR, we traverse each character of STR
from Step 2 to 3. If the character is in lower case, then it is converted into upper case by subtracting
32 from its ASCII value. But if the character is already in upper case, then it is copied into the
UPPERSTR string. Finally, when all the characters have been traversed, a null character is appended
to UPPERSTR (as done in Step 4).

3. Converting Characters of a String into Lower Case


✓ If we have to convert an upper case character into lower case, we need to add 32 to the ASCII
value of the character.
✓ Figure 13.8 shows an algorithm that converts the upper case characters of a string into lower case.
✓ In the algorithm, we initialize I to zero. Using I as the index of STR, we traverse each character of
STR from Step 2 to 3. If the character is in upper case, then it is converted into lower case by adding
32 to its ASCII value. But if the character is already in lower case, then it is copied into the Lowerstr
string. Finally, when all the characters have been traversed, a null character is appended to Lowerstr
(as done in Step 4).

4. 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.
✓ Figure 13.9 shows an algorithm that concatenates two strings. In this algorithm, we first initialize the
tow counters I and J to zero. To concatenate the strings, we have to copy the contents of the first
string followed by the contents of the second string in the third string new_str. Steps 2 to 4 copies the

B.I.E.T. Davangere 5
contents of first string in new_str. Likewise Steps 6 to 8 copies the contents of second string in
new_str. After the contents have been copied, a null character is appended at the end of new_str.

5. Appending a String to Another String


✓ Appending one string to another string involves copying the contents of the source string at the
end of the destination string.
✓ For example, if S1 and S2 are two strings, then appending S1 to S2 means we have to add the contents
of S1 to S2. So, S1 is the source string and S2 is the destination string. The appending operation
would leave the source string S1 unchanged and the destination string S2 = S2 + S1.
✓ Figure 4.5 shows an algorithm that appends two strings. In this algorithm, we first traverse through
the destination string to reach its end, i.e., reach the position where a null character is encountered.
The characters of the source string are then copied into the destination string starting from that
position. Finally, a null character is added to terminate the destination string

6. 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.
✓ Figure 4.6 shows an algorithm that compares two strings.
✓ In this algorithm, we first check whether the two strings are of same length. If not, then there is no
point in moving ahead as it straightaway means that the two strings are not same. However, if the two
strings are of the same length, then we compare character by character to check if all the characters

B.I.E.T. Davangere 6
are same. If yes, then variable same is set to 1 else if same = 0, then we check which string precedes
the other in dictionary order and print the corresponding message.

7. Reversing a String
✓ 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, and so on.
✓ Figure 4.7 shows an algorithm that reverses a string.
✓ In Step 1, I is initialized to zero and J is initialized to the length of the string-1. In Step 2, while loop
is executed until all the characters of the string are accessed. In Step 3, we swap the i th character of
STR with its jth character. In Step 4, the value of I is incremented and J is decremented to traverse
STR in the forward and backward direction respectively.

8. Extracting a Substring from Left


✓ 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.
✓ For example, if S1= “Hello World”, then Substr_Left(S1,7)=Hello w.
✓ The algorithm for extracting the first n characters from a string is shown below:
Step 1: [INITIALIZE] SET I = 0
Step 2: Repeat Step 3 to 4 while STR[I] != NULL AND I<N
Step 3: SET Substr[I] = STR[I]
Step 4: SET I = I+1

B.I.E.T. Davangere 7
[END OF LOOP]
Step 5: SET Substr[I] = NULL
Step 6: EXIT
Figure 13.13 Algorithm to extract first n characters from a string
✓ In Step 1, we initialize the index variable I with zero. In Step 2, a while loop is executed until all the
characters of STR have been accessed and I is less than N. In Step 3, the Ith character of STR is copied
in the Ith character of Substr. In Step 4, the value of I is incremented to access the next character in
STR. In Step 5, Substr is appended with a null character.

9. Extracting a Substring from Right


✓ In order to extract a substring from the right side of the main string we need to first calculate
the position from the left.
✓ For example, 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 o
characters - n.
✓ For example, if S1= “Hello World”, then Substr_Right(S1, 7) = o World
✓ Figure 13.14 shows an algorithm that extracts n characters from the right of a string.
Step 1: [INITIALIZE] SET I = 0, J = Length(STR)-N
Step 2: Repeat Step 3 to 4 while STR[J] != NULL
Step 3: SET Substr[I] = STR[J]
Step 4: SET I = I+1, J=J+1
[END OF LOOP]
Step 5: SET Substr[I] = NULL
Step 6: EXIT
Figure 13.14 Algorithm to extract n characters from the right of a string
✓ In Step 1, we initialize the index variable I to zero and J to Length (STR)-N so that J points to the
character from which the string has to be copied in the substring. In Step 2, a while loop is executed
until the null character in STR is accessed. In Step 3, the Jth character of STR is copied in the Ith
character of Substr. In Step 4, the value of I and J are incremented. In Step 5, Substr is appended with
a null character.

10. Extracting a Substring from the Middle of a string


✓ 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
characters/length of the substring.
✓ For example, if we have a string,
str[] = “Welcome to the world of programming”
then
SUBSTRING (str, 15, 5) = World
✓ Figure 4.8 shows an algorithm that extracts the substring from a middle of a string.

B.I.E.T. Davangere 8
✓ In this algorithm, we initialize a loop counter I to M. i.e., the position from which the characters have
to be copied. Steps 3 to 6 are repeated until N characters have been copied. With every character
copied, we decrement the value of N. The characters of the string are copied into a string called
substr. At the end a null character is appended to substr to terminate the string.

11. Inserting a String in Another String


✓ The insertion operation inserts a string S in the main text T at the k th position. The general
syntax of this operation is INSERT(text, position, string).
✓ For example, INSERT("XYZXYZ",3, "AAA") = "XYZAAAXYZ" Figure 4.9 shows an algorithm to
insert a string in a given text at the specified position. This algorithm first initializes the indices into
the string to zero. From Steps 3 to 5, the contents of NEW_STR are built. If I is exactly equal to the
position at which the substring has to be inserted, then the inner loop copies the contents of the
substring into NEW_STR. Otherwise, the contents of the text are copied into it.

12. Indexing
✓ This operation returns the position in the string where the string pattern first occurs.
✓ For example, INDEX("Welcome to the world of programming", "world") = 15
✓ However, if the pattern does not exist in the string, the INDEX function returns 0.

13. Deleting a string from the Main String


✓ The deletion operation deletes a substring from a given text.
✓ We can write it as DELETE(text, position, length).
✓ For example, DELETE("ABCDXXXABCD", 4, 3) = "ABCDABCD"

14. Replacing a Pattern with Another Pattern in a String


✓ The replacement operation is used to replace the pattern P1 by another pattern P2.
✓ This is done by writing REPLACE(text, pattern1 , pattern2 ).
✓ For example, ("AAABBBCCC", "BBB", "X") = AAAXCCC
("AAABBBCCC", "X", "YYY")= AAABBBCC

4.3 Miscellaneous String and Character Functions


4.3.1 Character Manipulation Functions
✓ Table 8.1 illustrates some character functions contained in ctype.h.

B.I.E.T. Davangere 9
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()
B.I.E.T. Davangere 10
{
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. strncpy(str1,str2,n): String Number Copy


✓ ‘strncpy()’ function is used to copy ‘n’ characters from the source string str2 to the destination string
str1.
Syntax : char *strncpy(char *str1, const char *str2, size_t n);
Where,
str1: it is the destination string.
str2: it is the source string.
n: n is the number of characters to be copied into destination string.

Ex: Write a C program to demonstrate the usage of strncpy().


#include<stdio.h>
#include<string.h>
void main()
{
char str1[10], str2[10]= “Computer”;
strncpy(str1,str2,3);
printf (“The Source String=%s\n The Destination String=%s”, str1,str2);
}
Output:
The Source String= Computer
The Destination String= Com

4. 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);
}

B.I.E.T. Davangere 11
Output:
The concatenated String=GoodMorning.

5. strncat(str1,str2,n)- String Number Concatenate


✓ The ‘strncat()’ function is used to concatenate or join n characters of string str2 to the end of string
str1.
Syntax: char *strcat(char *str1, const char *str2, size_t n);
Where,
str1: It is the first string
str2: It is the second string
n: It is the number of characters of string s2 to be concatenated.

Ex: Write a C program to demonstrate the usage of strncat().


#include<stdio.h>
#include<string.h>
void main()
{
char str1[15]= “Good”;
char str2[15]= “Morning”;
strncat(str1,str2,4);
printf(“The concatenated String=%s”,str1);
}
Output:
The concatenated String=GoodMorn.

6. strcmp(str1,str22): 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’.

B.I.E.T. Davangere 12
✓ “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

7. strncmp(str1,str2,n): String Number Compare


✓ This function is used to compare first n number of characters in 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 or specified numbers of
characters have been tested.
✓ 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, size_t n);
Where,
str1: It is the first string.
str2: It is the second string.
n: It is the number of characters to be compared.

Ex: Write a C program to demonstrate the usage of strcmp().


#include<stdio.h>

B.I.E.T. Davangere 13
#include<string.h>
void main()
{
char str1[10]=”Hello”;
char str2[10]=”Hey”;
if(strncmp(str1,str2,2)==0)
printf(“The first two characters in the strings are identical”);
else
printf(“The first two characters in the strings are not identical”);
}
Output:
The first two characters in the strings are identical

8. strchr()
✓ It takes a string and a character as input and finds out the first occurrence of the given character in the
string pointed to by the argument str.
✓ It will return the pointer to the first occurrence of that character; if found otherwise, return Null.

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

Ex: Write a C program to demonstrate the usage of strchr().


#include <stdio.h>
#include <string.h>
void main()
{
char string1[30] = "I love to write.";
char *pos;
pos= strchr(string1, 'w');
if(pos)
printf(“w is found at position %d”, pos);
else
printf(“w is not found”);
}
Output:
w is found at position 10

9. strrchr()
✓ It takes a string and a character as input and finds out the last occurrence of a given character in that
string.
✓ It will return the pointer to the last occurrence of that character if found otherwise, return Null.

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

Ex: Write a C program to demonstrate the usage of strrchr().


#include <stdio.h>

B.I.E.T. Davangere 14
#include <string.h>
void main()
{
char string1[30] = “Programming in C.";
char *pos;
pos= strrchr(string1, ‘n');
if(pos)
printf(“The last position of n is %d”, pos);
else
printf(“n is not found”);
}
Output:
The last position of n is 13.

10. strspn()
✓ The function returns the index of the first character in str1 that dosen’t match any character in str2.

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

Ex: Write a C program to demonstrate the usage of strspn().


#include <stdio.h>
#include <string.h>
main()
{
char str1[] = “HAPPY BIRTHDAY TO YOU";
char str2[]=“HAPPY BIRTHDAY JOE”;
printf(“The position of the first character in str2 that does not
match with that in str1 is %d”, strspn(str1,str2));
}
Output:
The position of the first character in str2 that does not match with that in str1 is 15

11. strcspn()
✓ The function returns the index of the first character in str1 that matches any of the characters in str2.
Syntax:
size_t strcspn( const char *str1, const char *str2);

Ex: Write a C program to demonstrate the usage of strcspn().


#include <stdio.h>
#include <string.h>
void main()
{
char str1[] = “PROGRAMMING IN C";
char str2[]=“IN”;
printf(“The position of the first character in str2 that match with
that in str1 is %d”, strcspn(str1,str2));
}
Output:
The position of the first character in str2 that match with that in str1 is 8
B.I.E.T. Davangere 15
12. strpbrk()
✓ 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.

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

Ex: Write a C program to demonstrate the usage of strpbrk().


#include <stdio.h>
#include <string.h>
void main()
{
char str1[] = “PROGRAMMING 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”);
}
Output:
character in str2 matches with that in str1

13. strtok()
✓ The strtok() function is used to isolate sequential tokens in a null –terminated string, str.
✓ It 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.

Syntax:
char *strtok(char *str1, const char *delimiter);

Ex: Write a C program to demonstrate the usage of strtok().


#include <stdio.h>
#include <string.h>
void main()
{
char str[] = "Hello, to, the, World of, Programming";
char delim[] =",";
char *result;
result = strtok(str,delim);
while(result!= NULL)
{
printf(“\n %s", result);
result = strtok(NULL,delim);
}
}

B.I.E.T. Davangere 16
Output:
Hello
to
the
World of
Programming

4.3.3 String Manipulation functions present in <stdlib.h>


1. strtol()
✓ The strtol() function converts the string pointed by str to a long value.
✓ The function skips the leading white space characters and stops when it encounters the first non-
numeric character.
✓ It stores the address of the first invalid character in str in *end.
✓ You may pass NULL instead of *end if you do not want to store any invalid characters anywhere.
✓ Third argument base specifies whether the number is Hexadecimal, binary, octal or decimal
representation.

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

Ex: Write a C program to demonstrate the usage of strtol().


#include <stdio.h>
#include <stdlib.h>
void main()
{
long num;
num = strtol(“12345 Decimal Value” , NULL, 10);
printf(“%ld”, num);
num = strtol(“65432 Octal Value” , NULL, 8);
printf(“%ld”, num);
num = strtol(“10110101 Binary Value” , NULL, 2);
printf(“%ld”, num);
num = strtol(“A7CB4 Hexadecimal Value” , NULL, 16);
printf(“%ld”, num);
}
Output:
12345
27418
181
687284

2. strtod()
✓ 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 the cases the number should be optionally followed by an exponent (‘E’ or ‘e’ for decimal
constants and ‘P’ or ‘p’ for hexadecimal constants).

B.I.E.T. Davangere 17
Syntax:
double strtod( const char *str, char **end );

Ex: Write a C program to demonstrate the usage of strtod().


#include<stdio.h>
#include<stdlib.h>
void main()
{
double sum;
num = strtod(“123.345abcdefg”, NULL);
printf(“%lf”, num);
}
Output:
123.345000

3. atoi()
✓ The atoi() function converts a given string passed to it as an argument into an integer.
✓ The function returns that integer to the calling function.
✓ However, the string should start with a number.
✓ The function will stop reading from the string as soon as it encounters a non-numerical character.

Syntax:
int atoi(const char *str);

Example:
i = atoi(“123.456”);
Result: i=123.

4. atof()
✓ This function converts the string that it accepts as an argument into a double value and then returns
that to the calling function.
✓ The string can be terminated with any non-numerical character other than “E” or “e”.
Syntax:
double atof(const char *str);

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

5. atol()
✓ This function converts the string into a long int value.
✓ This function will read from the string until it finds any character that should not be in long.

Syntax:
long atol(const char *str);

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

B.I.E.T. Davangere 18
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]);
}

B.I.E.T. Davangere 19

soprotection.com
Module 4
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.

Applications of pointer
✓ Pointers are used to pass information back and forth between functions.
✓ Pointers enable the programmers to return multiple data items from a function via function arguments.
✓ Pointers provide an alternate way to access the individual elements of an array.
✓ Pointers are used to pass arrays and strings as function arguments.
✓ Pointers are used to create complex data structures, such as trees, linked lists, linked stacks, linked
queues, and graphs.
✓ Pointers are used for the dynamic memory allocation of a variable.

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;

B.I.E.T. Davangere 1
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;

B.I.E.T. Davangere 2
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,

B.I.E.T. Davangere 3
#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()
{
int a,b, res; Output:
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);
}

B.I.E.T. Davangere 4
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

B.I.E.T. Davangere 5

inprotected.com

You might also like