Module-4
Module-4
• To store a string of length 5, we need 5+1 locations (1 extra for the null character).
• 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.
• When allocating memory space for a character array, reserve space to hold the null
character also.
• 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.
• The given statement declares a constant string as we have assigned value to it while
declaring the string.
• 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.
• 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[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:
• 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() 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
printf(“%s”, 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’).
i=0;
while(str[i]!=‘\0’)
{
putchar(str[i]); // Print the character on the screen
i++;
}
#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 |
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).
The syntax:
• 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.
#include<stdio.h>
int main()
{
char buf[100];
int num=10;
sprintf(buf, “num = %3d”, num);
}
• 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 *.
• 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”]
• 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.
• 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.
#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;
}
• 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:
• 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.
• 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.
Delimited String: In this the string is ended with a delimiter. The delimiter is then
used to identify the end of the string.
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.
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);
int i;
char ch = ‘A’;
i = ch + 10;
printf(“%d”, i);
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.
#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:
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.
#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++;
}
upper_str[j] = '\0';
printf("\n The string converted into upper case is:");
puts(upper_str);
return 0;
}
Output:
If we want to convert upper case character into lower case, then we just need to add 32
to its ASCII value.
#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++;
}
lower_str[j] = '\0';
printf("\n The string converted into upper case is:");
puts(lower_str);
return 0;
}
Output:
If S1 and S2 are two strings, then concatenation operation produces a string which
contains characters of S1 followed by the Characters of S2.
#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++;
}
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
#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:
If S1 and S2 are two strings then comparing two strings will give either of these
results.
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.
#include <stdio.h>
#include<string.h>
int main()
{
char str1[50], str2[50];
int i=0, len1=0, len2=0, same=0;
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)
{
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:
#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:
¨ 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.
#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
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
¨ 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.
int main()
{
char str[100], substr[100];
int i=0, j=0, n, m;
printf("\n Enter the string:");
gets(str);
¨ 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:
¨ 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.
#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;
{
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.
#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
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?
¨ 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
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.
#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
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.
Copying stops when n characters are copied or the terminating null character of str2 is
copied.
#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
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.
#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.
#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
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.
#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
strncmp Function:
Syntax:
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.
#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
strcpy Function:
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.
strncpy Function:
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.
#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
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;
}
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.
#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;
}
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
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.
#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
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.
#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;
}
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.
#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;
}
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
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
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.
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.
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);
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.
Example: x=atol(“12345.6789”);
Result: x=12345L.
¨ If there are 20 students in a class and we need a string that stores names of all the
20 students.
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.
#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
¨ 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.
¨ 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.
¨ 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.
¨ 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.
#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;
}
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
¨ 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.
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;
}
¨ 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.
¨ 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 = # ¨ 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
¨ 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.
¨ 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
¨ int ptr;
¨ ptr = 0;
¨ 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
¨ 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().
¨ 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:
#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