0 ratings0% found this document useful (0 votes) 56 views21 pagesModule 4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Principles of Progranuning Us
ny C (22POP13) 022
MODULE 4
Strings and Pointers
4.1 Introduction to Strings:
* A string is @ null-terminated character array. This means that afte
character, a null character (°\0} is stored to signify the end of the
array
* The general form of declaring a string is
char strjsize]
+ For example if we write,
char str|] ~ “HELLO”;
We are declaring a character array with 5 characters namely
L, Land O. Besides, a null character (‘\0}is stored at the end of the string. So, the
n of the string becomes- HELLO'\O’. Note that to store a string o
th 5, we need 5 ~ i 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,
H
char str|
“HELLO”:
‘str[0] 1000 H | Beginning of the string
st{i] 1001) E
‘str[2] 1002 |
EB
L
| roe
str(3] 1003 | L |
‘str[4] 1004 | “oO |
stz[5] 1005 | \O | Endof the String
char str[] = “HELLO”;
‘The forgiven statement declares a constant string as we have assigned value to it while
declaring the siring. However, the general form of declaring a string is
char str[size];
When we declaring the sting in this way, we can store size -1 characters in the array
because the last character would be null character,
Till now we have scen one way of initializing strings. The other way to initialize a string
is to initialize it as an array of characters, like
LL, 0%, \0%;
We can also declare a string with size much larger tha
are initialized.
For example, consider the statement below:
char str[10] = "HELLO";
In such cases, the compiler creates a character array of size 10, stores the values
“HELLO” in it and finally terminates the value with a null character. Rest of the
clements in the array are automatically initialized to NULL,
n the number of elements that
4.1.1 Reading String
If we declare a string by writing
char str{100};
‘Then str can be read from the user by using three
1. use scanf function
ays.
Maharaja Institute of Technology Mysore Dept. of Computer Science and Ei
TE
© scanned with OKEN ScannerPrincip
of Programming Using © (22POP13) &
2. using gets() funetio
3. using getchar(), getch{), getchar() functions repeatedly
The string can be read using seant() by writing,
seant{'%s", str);
Although the syntax of scanf{) function is well known and to use, the main pitfall
with this function is that the function terminates as soon as it finds a blank space.
‘or example, if the user enters Hello World, then str will contain only Hello.
+ The strin;
gets(str)
zets() takes the starting address of the string which will hold the input. The
string inputted using gets() is automatically terminated with a null character.
* The string can also be read by calling the getchar() repeatedly to read a sequence
of single characters (unless a terminating char tered) and
simultaneously storing it in a character array
i=0;
getehar(eh);
while(ch != '*)
{ striij=e
getchar(ch);
} strfi] ="\05
n be read by writing
riser
4.1.2 Writing String
‘The string can be displayed on screen using three ways
‘© use printf) function
* using puts() function
* using putchar()function repeatedly
The string can be displayed using printf) by writing
print{(*%s", str);
We use the conversion character ‘s’ to output a string, We may also use width and
precision specifications along with %s. The width specifies the minimum output field
ith. If the string is short, extra space is either left padded or padded. Th
precision specifies the maximum number of character to be displayed. If the string is
long, the extra character are truncated.
‘The string can be displaye
puts(str);
puts() is a simple function that overcomes the drawbacks of the printil) function. The
puts() function writes a line of output on the screen, It terminates the line with a
newline character(\n).
by writing
ly to print a sequence of
‘The string can also be written by calling the putchar() repeat
single characters
iO;
while(sts[i] = "\O*)
{ putchar(str[il};
it
}
4.2 Suppressing Input
The scanf{) 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 *. For example, given:
© scanned with OKEN Scanner
Maharaja Institute of Technology Mysore Dept. of CompuPrinciples of Programming Using © (22POP 1a)
scant’
The time can be read
assigned to anything,
whei
cota’, hr, &min)
as 9:05 as a pair
Therefore, assignment
7 part of what is input needs to be suppress
Here the colon would be read but not
Suppression is. particularly useinl
ed.
4.2.1 Using a Scanset
The ANSI standard added the new scanset f
used to define a set
corresponding string,
brack:
lure to the C
01 characters which may be read and assigned to the
* scanset is defined by placing the characters inside square
language
ets prefixes
int main()
id
char str[10];
printf{"\n Enter string:
scanfl"%{aeiou)", str };
printfl "The string is : %s", str);
return
The code will stop accepting character as soon as the user will enter a character
that is not a 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. For example, if you write
seanf("%[*aciou}", str };
4.3 String Taxonomy
In C, we can store string either in fixed-ler
shown in figure
gth format or in variable-length format as
=]
ia] [sewn]
Fixed Length String:
When storing a string I a fixed-length format, you néed to specify an appropriate size
for the string variable. If the size is too small, then you wil
elements in the string,
not be able to store
Variable Length String:
A batter option is to use a variable length in which the string can be expencted of
contracted to recommended the elements in it
Length Controlled String
Ina length controlled string, you need to specify the number if characters in the string
This count is used by string manipulation functions to determine the actual length of
the string variables.
Delimited Strings
In this format, the string is ended with a delimiter. The
identify the end of the string. For example, in English language every sentence is ended
with a full-stop (). Similarly, in C we can use any character such as comma,
semicolon, colon, dash, null character, ete, as the delimiter of
Maharaja Institute of Technolo et:
ay Mysore, Dept. of Computer Seience and
(& scanned with OKEN Scanner=e
paincipies of enema a usa
in pers. When
4 operations OF strings go with oe ven
1 OP ye manipulated 1? an expres i i
wpracter constant OF
fan integc!
vonverted into alt :
the system
char ch =“
i= ch
princi md”. i)
: : For
4.4.1 Finding the jength of a String ce ere
cea ve ior characters in the St 4g constitutes t 2 ieee ae
te TH «er sor ) an return 10. Note that even blank spaces
TexGTH( MIT Mysore”
8 in tae SGT does nt
0 and LENGTH(
pie:
oth the strings
cause 5
2 ase
» LENGTH(O}) y= 08
any character:
ALGORITHM TO CALCULATE THE LB)
Step 1: [INITIALIZE] SET I~
Step 2: Repeat Step 3 white STR[T] != NO"
step 3: SET I=1+1
[END OF LOOP]
step 4: SET LENGTH =!
Step 5: END
NGTH OF A STRING
an index of the str
n, Lis used as
library function */
In this algorithm
y+ Length without using
ginclude
ginclude
void main()
int len =O.
char str{10}:
printf Enter the string\n'):
gets(str)
while(str[i!="\O)
len = i
| Printf Length of the given string is: %d\n" len};
4.4.2 Converting Characters of a String i
s g into Upper Case
In memory the ASCII code of a characte i
ee AS A al er is stored instead of its real value. The AS!
rode for AZ varies From 65 1091 ‘and the ASCII code for a-z ranges from O7 Pisce
if w ve convert a lower case character int er case, ae
eae 32 from the ASCII value of the enereeee eee ee eae at
aA CONVERT THE CHARACTERS |
RS
THM TO CON eo OF STRING INTO UPPER CASE
step 2: Repeat Step 3 while STR{I] != ‘\0”
ep IF STR(1] > ‘a’ AND STR{I] <‘z’
Maharaja Institute of T ae Upperstelt = Stains?
inttute of Technology Mysore. De
5 pt. of Computer Science and E
pur Sdeccwnd Eres. | SB
(& scanned with OKEN Scanner{ Programming Using C (22POP 13)
ELSE
SET UpperstrI] = STRII]
(END OF IF)
[END OF LOOP}
Step 4: SET Uppersty[l] = ‘\O"
Step 5: EXIT
inis algorithm. | is used as an index of the string STR. | is initialized to 0. We
se each character from step 2 to 3. If the character is already upper case. then is
e el:
er ca!
ASCII value
subtracting 32 from it
4.4.3 Converting Characters of a String into Lower Case
If we have t
convert an upper case character to lower case, then we just need to add
i value. Below shows the algorithm that converts characters of a siring
ate lowe
‘ALGORITHM TO CONVERT THE CHARACTERS OF STRING INTO UPPER CASE
Step [Initialize] SET 1-0
Step 2: Repeat Step 3 while STRIT] != ‘\0"
Step IF STR{1] > ‘A’ AND STR{I] < ‘2’
SET Lowerstr[I] = STR{I] + 32
ELSE
SET Lowerstr{I] = STRII]
[END OF IF]
[END OF LOOP)
Step 4: SET Lowerstr[I] = ‘\O”
Step 5: EXIT
4.4.4 Concatenating two strings to form a new string
STF Si and $2 are two strings, then concatenation operation produces a string
which contains characters of $1 followed by the characters of S2
ALGORITHM TO CONCATENATE TWO STRINGS
Step 1. Initialize I =0 and J=O
Step 2. Repeat step 3 to 4 while I
Step 3. SET new_str(J] = str1(1]
Step 4. Set I =I+1 and J=J+1
[END of step2]
step 5. SET I-0
Step 6. Repeat step 6 to 7 while I <= LENGTH(str2)
Step 7. SET new.str[J] = str1[I]
Step 8. Set I=I¥1 and J=J+1
[END of step5]
Step 9. SET new_str[J] = ‘\0"
Step 10. EXIT
LENGTH(str1)
4.4.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 SI and $2 are two strings,
Shen appending $1 to 2 means we have to add the contents of SI to $2. so SI is the
source string and S2 is the destination string. The appending operation would leave
the source string $1 unchanged and destination string S2.= $2151
‘ALGORITHM TO APPEND A STRING TO ANOTHER STRING
Step 1: [Initialize] SET I =0 and J=0
‘Maharaja Institute of Technology Mysore. Dept. of Computer Science and Engs. |
(& scanned with OKEN ScannerPrmeiptes of Programing Using (22POP12)
Step 2: Repeat Step 3 while Dest Stiff] ‘\O"
Step 3: SETI+1+ 1
[END OF LOOP}
step 4: Repeat Step 5 to 7 while Source Str[J] != ‘\0"
Step 5: Dest Str[l] = Source Str{J]
Step 6: SETI=I+ 1
Step 7: SETJ=J +1
[END OF LOOP]
Step 8: SET Dest_Str[J] = ‘\0"
Step 9: EXIT
* Prog
inchade
include
void maint)
char stri{10}, str2[10};
printf("Enter First String:");
gets(strl);
printi(”\n Enter Second Str
gets(str2)
strcat(strl,str2}; //concatenates strl and str2
printf("\n Concatenated String is");
puts(strl); //resultant string is stored in str]
am to concatenates two string */
ee"):
/* Program to concatenates two string */
tinclude
sinclude
void main()
char strl[10}, str2{10};
int i-0,j
prinu{("Enter the String 1\n"):
getststr}};
print{("Enter the String 2\n");
gets(str2}
while(strfif!"\0)
1-0;
while(str2gl!=\0)
strlfil=str2li);
ms
str 1 fil="\0%
prinu{("Con
puts(stel);
ion of string as follows \n");
nology Mysore
© scanned with OKEN ScannerPrinciples of Programming Using © (22POPI3) ae
4.4.6 Comparing Two Strings
TEST andl S2 are two strings then comparing two strings will give ether of Tess
ts
a) $1 and S2are equal
b) Si=S2, when in dictionary order Si will come alter S2
hen in dictionary order $1 precedes S2
to compare the two strings, each and every character is compare
il the characters are same then the two strings are said to De equal
strings. If
Algorithm:
Step}: [Initialize] SET 1-0, SAME =O
Step 2: SET Lenl = Length(STR1), Len2 = Length{STR2)
Step 3: iF lenl != len2, then
Write “Strings Are Not Equal”
ELSE
Repeat while I STR2{I), then
Write “String! is greater than String?”
ELSE IF STR1[I] < STR2{], then
Write “String? is greater than String]”
[END OF IF]
(END OF IF]
step 5: BXIT
J+ Program to perform string comparison operation */
#includecstdio.h>
#include
nclude
void main()
int i-0;
int len1=0;
int len2=0;
char str1|50},str2|50};
int flag = 0;
print{('Enter the String 1\n");
getststrl};
printif'Enter the Strin;
gets(str2}
en = strlen(str 1};
ten? = strlen(str2};
if(lent = len2}
Maharaja Institute of Technology Mysore, Dept. 0
7 Computer Science and B
(& scanned with OKEN ScannerPrinciples of Programmung Using G (22POP 1) a
prinu(’Strings ae Not Equal\u’)
exit):
while(str][i]!="\0)
ifjstrlfij != su
break
ififlag == 0)
nufl'Strings are Equi
\n'k:
gs are Not Equal\n’)
4.4.7 Reversing a String
If Si= “HELLO™, then reverse of $1 = “OLLI
the first character with the
and so forth.
Hi”. To reverse a string we just
. second character with the second last character,
ALGORITHM TO REVERSE A STRING ee
Step1: [Initialize] SET I=0, J= Length(STR)
Step 2: Repeat Step 3 and 4 while I< Length(STR)
Step 3: — SWAP( STR(I), STR(J))
Step 4: SETI=1+1,J=J-1
[END OF LOOP}
Step 5: EXIT
4.4.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 $1 = “Hello World”, then Subste_Left(S1, 7) = Hello W
ALGORITHM TO EXTRACT N CHARCTERS FROM RIGHT OF A STRING
Step 1: [Initialize] SET I-0, J = Length(STR) - N+ 1
Step 2: Repeat Step 3 while STR(J] != ‘\0"
Step 3: SET Substr{l] = STR[J]
Step 4: SETI=1I41,J=J+1
[END OF LOOP}
Step S: SET Substr{t] ="\0"
Step 6: EXIT
4.4.9 Extracting a substring from right of the string
In order to extract a substring from the right side of the main string we need to first
culate the position. For ple, if SL = “Hello World” and we have to copy 7
characters starting from the right, then we have to actually start extracting characters
from the Sth position. This is calculated by, total number of characters =n + 1.
For example, if $1 = ‘Hello World”, then Substr_Right(S1, 7) = 0 World
ALGORITHM TO EXTRACT N CHARCTERS FROM RIGHT OF A STRING
Step 1: [Initialize] SET I=0, J = Length{STR) - N +1
Step 2: Repeat Step 3 while STR{J] != ‘\0"
Maharaia Institute of Technology Mysore Dept. of Compu
(& scanned with OKEN ScannerPrinciples of Progratimmng Using © 22POP 13)
Step 3: SET Substrll] = STRIJ]
Step4: SETI=1+1d=Jde1
[END OF LOOP|
Step 5: SET Substr[l] ="\0"
Step 6: EXIT
4.4.10 Extracting a substring from the Middle of a string
iven string requires information
of 5
+ maximum number of characters/length of the substring
or exampic, if we have a string,
sir|] = “Welcome to the world of programming”:
SUBSTRING|str. 15. 5) = world
Algorithm to extract substring from a given text
Step 1: [INITIALIZE] Set I=M, J =0
Step 2: Repeat steps 3 to 6 while str{f]
st characte
ringint
hen,
and N:
Step 3: SET substr[J] = str[l]
Step 4: SETI=I+1
Step 5: SETU=J+i
Step 6: | SETN=N-1
[END of loop]
Step 7: SET substr[J] = ‘\0"
Step 8: EXIT
4.4.11 Inserting a String in Another string
‘The insertion operation inserts a string $ in the main text, T «
general syntax of this operation is: INSERT(text, pos
INSERT(*XYZXYZ", 3, “AAA") TANAXYZ,
Algorithm to insert a string in the main text
Step 1: [INITIALIZE] SET I=0, J=O and K-0
Step 2: Repeat steps 3 to 4 while textI] !
Step 3: IF I= pos, then
Repeat while str[K]
new str{j] = str[k]
\o"
SET J-J+1
SET K = K+1
[END OF INNER LOOP|
ELSE
new_str[{J] = text{t]
SET J = J+1
[END OF IF]
: SET T= 1+1
[END OF OUTER LOOP]
Step 5: SET new_str[J] = ‘\0"
Step 6: EXIT
Step
4.12 Indexing
Ind ion returns the position in the strin,
For example,
INDEX(“Welcome to the world of programming”, “world’) = 1
However, if the in the string, the INDE
1 where the stri
attern does not 9
Maharaja Institute of Technology Mysore
Dept. of Computer
vbout thr
the kth position.
ion, string). For
ng pattern first occurs,
function returns 0.
nice and Eng. | B_ J
(& scanned with OKEN ScannerPrinciples of Programming tency ©: (22POP 13)
Algorithm to find the index of the first oceurrence of a string wit
Step 1
na given text
: [Initialize] SET I=0 and MAX = LENGTH(text) ~ LENGTH(str) +1
Step 2: Repeat Steps 3 to 6 while | <= MAX
Step 3: Repeat step 4 for K = 0 To Length(str)
Step 4:
IF str{kK] != text{I + K], then GOTO step 6
[END of inner loop}
Step 5: SET INDEX =I. Goto step 8
Step 6: SETI=I+i
[END OF OUTER LOOP]
Step 7: SET INDEX = -1
Step S: EXIT
4.4.18 Deleting a String from the Main String
jon operation deletes a subs
(ce: ength}
For exemple, DELETE(ABCDXXXABCD’, 5, 3) = “ABCDABCD”
Algorithm to delete a substring from a text
Step 1: [INITIALIZE] SET I=0 and J=0
Step 2: Repeat steps 3 to 6 while text[l] !="\0"
Step3: IF I=M, then
Repeat Step 4 while N>=
‘om a
SETN=N-1
[END of inner loop]
(END OF IF]
Step 4: SET new_str[J] = text{I]
Step
Step
[END of outer loop]
Step 7: SET new_str[J] = ‘\0"
Step 8: EXIT
4.4.14 Replacing a Pattern with Another Pattern in a String
* Replacement ope used to replace the pattern
This is done by writing, REPLACE(text, pattern1, pattern2)
«For example, (AAABBBCCC’, “BBB”,
* (AAABBBCCC’, “NX”. “YYY")= AAABBBCC
"in tne second exemple there is no change as ‘NX’ does not appear in the text
Algorithm to replace a pattern Py with another pattern P2 in the given text TEXT
Step 1: [INITIALIZE] SET Pos = INDEXITEXT, Ps)
Step 2: SET TEXT = DELETE(TEXT, Pos, LENGTH(P1))
Step 3: INSERT(TEXT, Pos, P2)
Step 4: EXIT
4.5 String Manipulation Function
+ Strings are often needed to be manipulated by programmer according to the ne ed ofa
problem
pret curing, manipulation can be done manually by the programmer but this makes
programming, complex and lar;
ooeestive this, the C supports a large number of string handling functions
v There are numerous functions defined in header file
Dept. of Computer Seience and En
ed
(& scanned with OKEN Scannerprineiples of Programming Using G (22POP13)
sat, Function & Purpose
repytst. Sh:
_sitlentst):
32h
oestond
suchelst
Reumea porter te
i
sursvist. $2:
Serums seerter
streat Function
Syntax:
‘char *streat(char * str1, char *str2);
e stent function appends the string pointed by str2 to the end of the string
co by stel.-The terminating nuil character of su is overwritten. The process St
sence tne terminating null character of str2 is copied
y Example: Program to illustrate the use of streat)-
include
#include
void main()
char stri[10}, str2[10};
print{{'Enter First Strings");
gets(strl);
print{{’\n Enter Second String:
gets(str2)
aereat{otr L-str2}; //eoncatenates strl and str? and
printi(’\n Concatenated String is")
puts(str): //resultant string is stored in strl
strneat Function
Synta:
char *strneat(char * stri, char *str2, size_t n)i
“The stmneat funetion appends the string pointed by str2 10 the end of the string pointed
toby sul up to p characters long. The terminating null character of str is
vo op uritten, The coping stops when n character of str2 is copied
* Example: Program to illustrate the use of strmeat()-
#include
include
void main()
char str][10}, str2[10};
print{("Enter First String:"};
getststrl);
print{("\n Enter Second Strin}
gets(str2);
steneat(strl,str2, 4);
Tahar Ino oF eel MSN ep of Gamputer sence and Ewa 1 [EEC
© scanned with OKEN ScannerSe era eee
3?
Principles of Programming Using C (22POP13) 029 oS
print("\n Concatenated String is
putsfstr]);
strepy Function
Syntax;
char “strneat(char * str, char “str2);
nena ee ee String pointed to by sir? to str] including the null chara
sr. i returns the argument str]. Here str
1 should be hig enough to store the conten
- #include
nclude
void main()
char str 20}. str2{20}
prinf("Enter string: °)
gets(str2);
strepy(str, str2); /Content of string sre is copied to string dest
printi("Copied string: *)
puts(strl):
Output:
Enter string: mitmysore
Copied string: mitmysore
strnepy Function
Syntax:
char “strneat(char * str, char “str2, size_t n);
This function copies up to n character from the string pointed to by str2 to strl
Gopsing stops when a characters are copied. However, If the null character is reached
then the null character is continually copied to stri until n characters have been
copied. Finally, a null character is appended to strl. However, if n is zero or negative
then nothing is copied.
#includecstring.h>
\clude
void main()
char str [20]. str2|20|:
prinuf('Enter string: ");
gets(str2);
strepy(strl, str2, 3);
printi("Copied string:
puts(str]);
strlen Function
Syntax:
Size_t strlen(const char * str};
This function calculates the length of the string str up to but not including the null
character, i.¢., the function returns the number of characters in the string,
Example: Program to illustrate the use of strlen().
#includeestring.h>
Hinclude
Vaharaja Intute of Technolog Mrsore Dept of Gomer Science and Bras T
(& scanned with OKEN Scannerprinciples of Programmang Using © (2
vik uaunnl)
sty{20}
int len;
is ww be found:’)
prinu( Enter siring whose le
gers(ck
jen=strlenistr}
of the string is Yd". Jeni:
jnt stremp(const char * stri, const char “str2);
‘n compares the string pointed :o by strl to the string poin
veturns zero if the strings are equal. Otherwise. it returns @ “al
than or greater than str2 respectivels
‘xample program:
ide
clude
nain()
char stri{30},str2{30]>
printi("Enter first string:
gets(strl}s
print{(Enter second string:
gets(str2);
ifjstremp(str1,str2)=-0)
printi(’Both strings are equal}
else
printif’Strings are unequal};
Output:
Enter First String:
MIT
Enter Second Sting:
Mysore
Strings are unequal
Output:
Enter First String:
MIT.
Enter Second String:
MIT
Both strin
are equal
strnemp function
synte
int stremp(const char * str1, const char *str2, sizet
The sumemp hinction compares at most the first n bytes of strl and str2. ‘The process
claps comparing after the null character is encountered, The funtion returns zero if
serfs m bytes of the strings are equal, Otherwise, it returns a value less than or
greater than zero if stt1 is less than or greater than str2, respectively
wengs. | BB
© scanned with OKEN Scanner
Maharaja Institute of Technology Mysore. Dept. of Computer SciencePrinciples of Progr
mming Using © (2213)
Hinchude <
Example py
string li
Hinchudesstdio.by
void main()
char str (30),s t
prinu{ Enter first string: |
geis(strl}:
prinufEnter
getsistr2);
ifjstrnemp(
printl("Both st
else
printi’Strings are unequa!
‘ond string:
ri,str2.2)==0)
ings are equal
strstr function
syntax:
char “strstr(const char * str, const char *str2);
This function is used 10 the first occurrence of string str2 {not including th
toes inating null character) in the strl. It returns a pointer to the first occurrence 0!
tr? in stri, If no match if found, then a null pointer is returned,
#include
#include
void main()
char str1[30},str2{30|;
char *ptr:
printi(Enter first string: ")
gets(strl);
printi(Enter second string: ")
getststr2):
pir = strstr(strl,str2)
ifipt)
print{{’Substring Found’):
else
print{("Substring not found”):
atoi{) Function
The stoi function converts a character string to an inteast value:
sequence of characters that can be interpreted as a numeric value of the specified
seaarn type. The function stops reading the inpur Vine ‘at the first character that it
cei aceenlee as\ pert ol a:numibet Me lee rac sae be the null character that
ends the string,
The atoil) function doe:
The string argument for this function has the form:
int atoi{eonst char *str};
nores leading, white-space
‘The input string i:
mal points or exponents.
not recognize de
characters. The value digits represen!
‘The atoi() function
one or more decimal digits.
Ex: i = atoi(*!23.456");
Result i = 123.
iene | BB]
Dept, of Comput
Teakaraia Institute of Technology Mysore.
© scanned with OKEN Scanner/ principles of Programming Using CG (22POP13)
atof () Funetion
in the C Programming Language, the atof funetion converts a string to a floatin:
huumber (double)
The atof function skips all white-space characters at the beginning of the string,
converts the subsequent characters as part of the number, and then stops when it
encounters the first character that isn’t a number
mtax
The s
ntax for the atof function in the C Language i
double atof{const char *str};
cre str is pointer to a string to convert to a Mloati
X = atof{“12.39 is the answer”
Result: X= 12.39
4.6 Arrays of Strings
«Now suppose that there are 20 students in a class and we need @ string that
stores names of all the 20 students. How can this be done? Here. we need &
string of strings or an array of strings. Such an array of strings would store 20
individual sttings. An array of string is declared as,
char names{20][30];
«Here, the first index will specify how many strings 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 maximum 30 characters long,
= Letus sce the memory representation of an array of strings. If we have an array
declared as,
char name(5I|10] = "Ram", “Mohan”, “Shyam”, “Hari”, Gopal”);
yamelol| p| a | ue [40°
mM, o| HH} A | N /‘\0"
Namel2]| |u| ¥ | a | m [10°
Name(3]) | A] R | 1 [No
o|pla|u lo
|
i
Name[4] [¢
#includeestdio.h>
#include
void main()
char names|5}[ 10];
int i, nj
clrserl);
prinu{é\n Enter the number of students:
scant{%d”, &n);
for(i=O;icnjit 4)
Maharaja Institute of Technology Mysore, Dept. of Compu
Scenes and Eng |
(& scanned with OKEN Scanner: ath smdent | * i UE
printit?\n Enter the name of %adth st den )
gets(namesti))
print{{*\n Names of the students are : \n"}
for(i=Osisna> >)
puts(names|i}}
getcht):
CHAPTER POINTER
4.7 Understanding The Computer's Memory.
Every computer has a primary memory. All our data and programs need to be placed
in the primary Yor execution
The primary memory or RAM (Random Access Memory which is a part of the primary
memon) is a collection of memory locations (often known as cells) and each location
has a specific address. Each memory location is capable of storing 1 byte of data
Generally, the computer has three areas of memory each of which is used for a specific
task. These areas of memory include- stack, heap and global memory
* Stack- A fixed size of 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. That is,
the last element added to the stack is removed first.
* Heap- Heap is a contiguous block of memory that is available for use by the
program when need arise. A fixed size heap is allocated by the system and is
used by the system in a random fashion.
* When the program requests a block of memory, the dynamic allocation
technique carves out a block from the heap and assigns it to the program.
When the program has finished using that block, it returns that memory block to the
heap and the location of the memory locations in that block is added to the free list
* Global Memory- The block of code that is the main() program (along with other
functions in the 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 functién.
Besides. the function code, all global variables declared in the program are
stored in the global memory area.
* Other Memory Layouts- C provides some more memory areas like- text
segment, BSS and shared library segment.
« The text segment is used to store the machine instructions corresponding to the
compiled program. This is generally a read-only memory segment
«BSS is uscd to store un-initialized global variables
Shared libraries segment contains the executable image of shared libraries that
are being used by the program.
4.8 Introduction to Pointers
Every variable in C has a name and a value associated with it, When a variable
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
Lx = 10;
‘Maharaja Institute of Technology Mysore. Dept. of Computer Seience and
© scanned with OKEN ScannerPrinciples of Programming Using © (22POPI3) 2022
* When this 5
atement executes. the compiler sets aside 2 bytes of memory to hold
the value 10. It also sets up at symbol table in which it adds the svmbol x and
ive address in memory where those J bytes were set aside:
* Thus, every variable in C has a value and an also @ memory location (commonly
Known as address) associated with it. Some texts use the term rvalue and [value
for the value and the address of the variable respectively
© ‘The rvalue appears on the right side of the assignment statement and cannot be
used on the left side of the assignment statement. Therefore. writing 10 = k: is
Nega
ly pointers are nothing but memory addresses. A pointer is @ variable that
ains the memory location of another variable.
Pointers are frequently used in C language as they have a number of usefull
applications. These applications include:
+ For passing the argument by using references.
= For accessing the elements of an array.
= For dynamic memory allocation by using malloc() and calloc() functions
+ Used in arrays, functions to improve the performance of code.
+ For returning multiple values.
+ Implementing a data structure
ystem-level programming.
+ For doing s
4.9 Declaring Pointer Variables
4 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 variable
data_type *ptr_name;
Here, data_type is the data type of the value that the pointer will point to, For example:
int *pnum:
char *pch;
float *pinum;
int x= 10;
int *ptr = Gx;
‘The * informs the compiler that ptr is a pointer variable and the int specifies.
that it will store the address of an integer variable.
“The & operator retrieves the Ivalue (address) of x, and copies that to the contents
of the pointer ptr.
Example:
include
int main()
t
int num, ‘pnum;
pnum = #
printf“\n Enter the number : “);
Maharaja inatitute of Technology Mysore. Dep. of Computer Science eae
1
© scanned with OKEN Scannernciples of Programming Using C
OP 13)
seanf("ad”, Gnum); ;
print{(*\n The number that was entered is
return 0;
2 %d", *pnum);
OUTPUT:
Enter the number : 10
‘The number that was entered is : 10
4.10 Pointer Expression and Pointer Arithmetic
ike other variabies, pointer variables can also be used in expressions.
For example, if ptr and ptr2 are pointers, then the following statements are valid.
For
When using pointers, unary increment (++) and decrement (
sum=0. mui-0.
ptrl = &numi, ptr2 = @num2;
sum = *pirl + *ptr2;
mul = sum °*pirl
/*ptr2 - 30;
We can add integers to or subtract integers from pointers as well as to subtract
one pointer from the other.
We can compare pointers by
example p! > p2, pl==p2 and p
elational operators in the expressions. For
p2 are all valid in C.
operators have greater
precedence than the dereference operator (*). Therefore, the expression
ptr+> is equivalent to *[ptr+4). So the expression will increase the value of ptr so that
it now points to the next clement.
In order io increment the value of the variable whose address is stored in ptr, write
(rptr)++
Maharaja Institute of Technology Mysore. Dept. of Computer Seienc
ample Programs:
#include «stdi
const int MAX
void main ()
int vari]
int i, “pur;
/* let us have array addr
ptr = var;
for ( i = 0; i < MAX; i+)
10, 100, 200};
sin pointer */
printi("Address of var[%dl] = %x\n", i, ptr J;
print((’Value of var[%d] = %d\n", i, "ptr };
/* move to the next location */
pret;
«1 |
© scanned with OKEN Scanner
\/srinciples of Programming Using ( 2022
Hinchade , and .
After including any of these files in vour program, write
int “ptr = NULL;
You can always check whether
or contains a null by writing,
if ( ptr == NULL)
ss of some variable
1 given pointer variable stores addr
Statement block;
:
Null pointers are used in. situations if one of the pointers in the program points
somewhere some of the time but not all of the time. In such situations it is alway
better to set it to a null pointer when it doesn’t point anywhere valid, and to test to see
if it’s a null pointer before using it
Maharaja Institute of Technology Mysore. De
© scanned with OKEN Scanneres
ata type: The void pointer
412 Geter dnt me ct ware
jninter is pointer Var iable cr an be US
ee ter fal type of Powter -
an d keyword a5 thi
nis inter val jable but using the vor 1 ke}
pointer
times. For eX.
sinchude
void main()
int x=10;
char ch
void “EP:
gp = 6 - -
Srintf("\n Generic pointer points to the fi
ach; :
printf"\n
nteger value = %d", *lint*)EP):
Generic pointer now points to the character ee", *(char*) EP)?
OUTPUT:
Generic pointer point
Generic pointer now
ts to the integer value = 10
points to the character = A
4.13 Passing Arguments to Function Using Pointers
Using call-by-value method, it is impossible to modify the actual param!
pass them to a function. Furthermore, the incomint arguments 10
pass das local variables in the function and those local ve iables get 2
5 passed from their calling function
eters when you
a function are
copy of the
valu
Pointer provide a mechanism to modify data declared in one function using code
written in another function
‘The calling function sends the addresses of the variables and the called function
iret declare those incoming arguments as pointers. In order to modify the
mest us cent by the caller, the called funtion must dereference the pointers thax were
passed to it. Thus, passing, pointers to a funtion avoid the overhead of copyin data
from one function to another.
Hence, to use pointers for passing arguments to a function, the programmer must do
the following:
+ Declare the function parameters as pointers
+ Use the dereferenced pointers in the function body
© Pass the addresses as the actual argument when the function is
dinclude
void main()
alled.
int num1, num2, total;
print{{“\n Enter two numbers : “);
seanf(%d %d”, &num1, &num2)
a Institute of Technoloyy’ Mysore. Dept. of Computer Si
Mahara
1 Bd
nce and Eng.
© scanned with OKEN Scanner4
Fg programming Using C (
OP 13)
sum(&num 1, &num2, &total):
print(("\n Total = %d”, total):
void sum (int *a, int “b, int +t)
“t= 4a + 4b.
gxumple Program:
include
void cal_area(foat, fost, foat, Noa)
int validateffioat. fioat, float): f
void main()
float a. b. ¢. area:
prin Enter values of 3 sides of a Triangle. \n"};
scanf('%M%Pf", Ka, &b, &c):
ifl validate(a, b. ¢) )
cal_areaia, b. c, &area)
printi(’Area of Triangle is %0.21\n",
cali
else
printi{’Please enter valid values for sides of Triangle.\n’);
void cal_area(float x, float y, float z, float A}
float S;
y +2) / 2.0; E
A= sqrlS (8-9) (S-y 7 S aM
int validate(float x, float y, float 2)
int flag = 0:
iffy > y &8& x > 2)
flag=(x #)
* nag =(y< (std)
else
flag = (2< (x + y)}
" return(flag);
Maharaja Institute of Technology Mysore. Dept. of Computer Science and E
wt |
© scanned with OKEN Scanner
You might also like
Strings: Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere
Strings: Dr. Azizkhan F Pathan, Prof. Meghana G R, Prof. Kotramma T S, Dept. of CS&E, JIT, Davangere
19 pages