Bpops103 M 4 Strings N Pointers - Notes
Bpops103 M 4 Strings N Pointers - Notes
Programming using C
MODULE-4 Notes
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.
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.
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++;
}
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.
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).
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.
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.
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.
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.
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.
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
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
B.I.E.T. Davangere 11
Output:
The concatenated String=GoodMorning.
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’.
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.
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);
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);
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 );
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);
Syntax:
char *strpbrk( const char *str1, const char *str2 );
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);
B.I.E.T. Davangere 16
Output:
Hello
to
the
World of
Programming
Syntax:
long strtol( const char *str, char **end, int base );
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 );
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.
Example:
1. int *ptr; // declares a pointer variable ptr of integer type.
2. float *temp; // declares a pointer variable temp of floating type.
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
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 = #
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.
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
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