0% found this document useful (0 votes)
2 views26 pages

POPC-Module4 Notes

Module 4 covers the fundamentals of strings and pointers in C programming, explaining that strings are null-terminated character arrays. It details various operations on strings, such as reading, writing, finding length, converting case, concatenating, appending, comparing, and reversing strings, along with sample code for each operation. The document emphasizes the importance of proper memory allocation and the use of functions like scanf, gets, printf, and others for string manipulation.

Uploaded by

mohankumar.g
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views26 pages

POPC-Module4 Notes

Module 4 covers the fundamentals of strings and pointers in C programming, explaining that strings are null-terminated character arrays. It details various operations on strings, such as reading, writing, finding length, converting case, concatenating, appending, comparing, and reversing strings, along with sample code for each operation. The document emphasizes the importance of proper memory allocation and the use of functions like scanf, gets, printf, and others for string manipulation.

Uploaded by

mohankumar.g
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE 4

Strings and Pointers


4.1 Introduction
 “A string is a sequence of characters enclosed within double quotes”. or
 “String is an array of characters and terminated by NULL character which is denoted by ‘\0’.
 In C, a string is a null-terminated character array.
 This means that after the last character, a null character ('\0') is stored to signify the end of the
character array.
For example, if we write char str[] = "HELLO";
we are declaring an array that has five characters, namely, H, E, L, L, and O. Apart from these characters,
a null character ('\0') is stored at the end of the string. So, the internal representation of the string becomes
HELLO'\0'. To store a string of length 5, we need 5 + 1 locations (1 extra for the null character). The
name of the character array (or the string) is a pointer to the beginning of the string.
 Figure 4.1 shows the difference between character storage and string storage.

 If we had declared str as


char str[5] = "HELLO";
then the null character will not be appended automatically to the character array. This is because str can
hold only 5 characters and the characters in HELLO have already filled the space allocated to it.
 Like we use subscripts (also known as index) to access the elements of an array, we can also use
subscripts to access the elements of a string. The subscript starts with a zero (0). All the characters
of a string are stored in successive memory locations. Figure 4.2 shows how str[] is stored in the
memory.

1
 ASCII code of a character is stored in the memory and not the character itself. So, at address 1000, 72
will be stored as the ASCII code for H is 72. The statement char str[] = "HELLO";
Syntax:
the general form of declaring a string is
char str[size];
 The other way to initialize a string is to initialize it as an array of characters. For example,
char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};
Here, the compiler will automatically calculate the size based on the number of characters.
 We can also declare a string with size much larger than the number of elements that are initialized.
For example, consider the statement below.
char str [10] = "HELLO";
In such cases, the compiler creates an array of size 10; stores "HELLO" in it and finally terminates
the string with a null character. Rest of the elements in the array are automatically initialized to NULL
 Now consider the following statements:
char str[3];
str = "HELLO";
The above initialization statement is illegal in C and would generate a compile-time error.

4.1.1 Reading Strings


 If we declare a string by writing char str[100]; Then str can be read by the user in three ways:
1. using scanf function,
2. using gets() function, and
3. using getchar(),getch()or getche() function repeatedly.

using scanf()
 Strings can be read using scanf() by writing scanf("%s", str);
 Unlike int, float, and char values, %s format does not require the ampersand before the variable str.
 The main pitfall of using this function is that the function terminates as soon as it finds a blank
space. Therefore we cannot read the complete sentence using scanf() function.

using gets()
 The string can be read by writing gets(str);
 gets() is a simple function that overcomes the drawbacks of the scanf() function.
 gets() function is used to read a sequence of characters (string) with spaces in between.
 The ‘gets()’ function allows us to read an ‘entire line’ of input including whitespace characters.
 The gets() function takes the starting address of the string which will hold the input.
 The string inputted using gets() is automatically terminated with a null character.

using getchar()
 Strings can also be read by calling the getchar() function repeatedly to read a sequence of single
characters (unless a terminating character is entered) and simultaneously storing it in a character
array as shown below:
i=0;
ch = getchar;// Get a character
while(ch != '*')
{
str[i] = ch;// Store the read character in str
i++;
ch = getchar();// Get another character
}
str[i] = '\0';// Terminate str with null character

2
4.1.2 Writing Strings
 Strings can be displayed on the screen using the following three ways:
1. using printf() function
2. using puts() function, and
3. using putchar() function repeatedly.

using printf()
 Strings can be displayed using printf() by writing printf("%s", str);
 We use the format specifier %s to output a string. Observe carefully that there is no ‘&’ character
used with the string variable.
 We may also use width and precision specifications along with %s.
 The precision specifies the maximum number of characters to be displayed, after which the string is
truncated. For example, printf ("%5.3s", str); The above statement would print only the first three
characters in a total field of five characters. Also these characters would be right justified in the
allocated width.
 To make the string left justified, we must use a minus sign. For example, printf ("%–5.3s", str);

using puts()
 A string can be displayed by writing puts(str);
 puts() is a simple function that overcomes the drawbacks of the printf() function.
 The puts() function writes a line of output on the screen. It terminates the line with a newline
character (‘\n’).

using putchar()
 Strings can also be written by calling the putchar() function repeatedly to print a sequence of
single characters.
i=0;
while(str[i] != '\0')
{
putchar(str[i]);// Print the character on the screen
i++;
}
4.2 Operations on Strings
1. Finding Length of a String
 The number of characters in a string constitutes the length of the string. For example,
LENGTH("C PROGRAMMING IS FUN") will return 20. Note that even blank spaces are counted as
characters in the string.
 Figure 4.3 shows an algorithm that calculates the length of a string. In this algorithm, I is used as an
index for traversing string STR. To traverse each and every character of STR, we increment the value
of I. Once we encounter the null character, the control jumps out of the while loop and the length is
initialized with the value of I.

3
Write a Program to find the length of a string.

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

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

Write a program to convert characters of a string into uppercase.

#include <stdio.h>
int main()
{
char str[100], upper_str[100];

4
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:
Enter the string: hello
The string converted into upper case is : HELLO

3. Converting Characters of a String into Lower Case

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

Write a program to convert characters of a string into lowercase.

#include <stdio.h>
int main()
{
char str[100], lower_str[100];
int i = 0, j = 0;
printf("\n Enter the string :");

5
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 lower case is : ");
puts(lower_str);
return 0;
}
Output:
Enter the string: HELLO
The string converted into lower case is : hello

4. Concatenating Two Strings to Form a New String

 If s1 and s2 are two strings, then concatenation operation produces a string which contains
characters of s1 followed by the characters of s2.
 Figure 13.9 shows an algorithm that concatenates two strings. In this algorithm, we first initialize the
tow counters I and J to zero. To concatenate the strings, we have to copy the contents of the first
string followed by the contents of the second string in the third string new_str. Steps 2 to 4 copies the
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.

Write a Program to concatenate two strings.

#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);

6
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 : Hello
Enter the second string : How are you?
The concatenated string is: Hello, How are you?

5. Appending a String to Another String

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

Write a program to append a string to another string.


#include <stdio.h>
int main()
{
char Dest_Str[100], Source_Str[50];

7
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++;
}
Dest_Str[i] = '\0';
printf("\n After appending, the destination string is: ");
puts(Dest_Str);
return 0;
}
Output:
Enter the source string: How are you?
Enter the destination string: Hi,
After appending, the destination string is: Hi,How are you?

6. Comparing Two Strings

 If S1 and S2 are two strings, then comparing the two strings will give either of the following
results:
(a) S1 and S2 are equal
(b) S1>S2, when in dictionary order, S1 will come after S2
(c) S1 <S2, when in dictionary order, S1 precedes S2
 To compare the two strings, each and every character is compared from both the strings. If all the
characters are the same, then the two strings are said to be equal.
 Figure 4.6 shows an algorithm that compares two strings.
 In this algorithm, we first check whether the two strings are of same length. If not, then there is no
point in moving ahead as it straightaway means that the two strings are not same. However, if the two
strings are of the same length, then we compare character by character to check if all the characters
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.

8
Write a Program to compare two strings.
#include <string.h>
#include <stdio.h>
int main()
{
char str1[50], str2[50];
int i = 0, len1 = 0, len2 = 0, same = 0;
printf("\n Enter the first string: ");
gets(str1);
printf("\n Enter the second string: ");
gets(str2);
len1 = strlen(str1);
len2 = strlen(str2);
if (len1 == len2)
{
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 string2");
else if (str1[i] < str2[i])
printf("\n String2 is greater than string1");
}
return 0;
}

9
Output:
Enter the first string: Hello
Enter the second string: Hello
The two strings are equal

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

Write a program to reverse the given string.

#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];
str[i] = temp;
i++;
j--;
}
printf("\n The reversed string is: ");
puts(str);
return 0;
}
Output:
Enter the string: Hi there
The reversed string is: ereht iH

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

Write a program to extract the First n characters of a string.

#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("\n Enter the number of characters to be copied: ");
scanf("%d", &n);
j = strlen(str) - n;
while (str[j] != '\0')
{
substr[i] = str[j];
i++;
j++;
}
substr[i] = '\0';
printf("\n The substring is : ");
puts(substr);
return 0;
}

Output:
Enter the string: Hi there
Enter the number of characters to be copied: 2
The substring is : Hi

11
9. Extracting a Substring from Right

 In order to extract a substring from the right side of the main string we need to first calculate
the position from the left.
 For example, if S1= “Hello World” and we have to copy 7 characters starting from the right then we
have to actually start extracting characters from the 4th position. This is calculated by total number o
characters - n.
 For example, if S1= “Hello World”, then Substr_Right(S1, 7) = o World
 Figure 13.14 shows an algorithm that extracts n characters from the right of a string.
Step 1: [INITIALIZE] SET I = 0, J = Length(STR)-N
Step 2: Repeat Step 3 to 4 while STR[J] != NULL
Step 3: SET Substr[I] = STR[J]
Step 4: SET I = I+1, J=J+1
[END OF LOOP]
Step 5: SET Substr[I] = NULL
Step 6: EXIT
Figure 13.14 Algorithm to extract n characters from the right of a string

 In Step 1, we initialize the index variable I to zero and J to Length (STR)-N so that J points to the
character from which the string has to be copied in the substring. In Step 2, a while loop is executed
until the null character in STR is accessed. In Step 3, the Jth character of STR is copied in the Ith
character of Substr. In Step 4, the value of I and J are incremented. In Step 5, Substr is appended with
a null character.

Write a program to extract the last n characters of a string.

#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("\n Enter the number of characters to be copied: ");
scanf("%d", &n);
j = strlen(str) - n;
while (str[j] != '\0')
{
substr[i] = str[j];
i++;
j++;
}
substr[i] = '\0';
printf("\n The substring is : ");
puts(substr);
return 0;
}
Output:
Enter the string: Hi there
Enter the number of characters to be copied: 5
The substring is : there

12
10. Extracting a Substring from the Middle of a string

 To extract a substring from a given string requires information about three things. The main
string, the position of the first character of the substring in the given string and the number of
characters/length of the substring.
 For example, if we have a string,
str[] = “Welcome to the world of programming”
then
SUBSTRING (str, 15, 5) = World
 Figure 4.8 shows an algorithm that extracts the substring from a middle of a string.

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

Write a program to extract a substring from a string.


#include <stdio.h>
int main()
{
char str[100], substr[100];
int i, j = 0, m, n;
printf("\n Enter the main string: ");
gets(str);
printf("\n Enter the position from which to start the substring: ");
scanf("%d", &m);
printf("\n Enter the length of the substring: ");
scanf("%d", &n);
i = m;
while (str[i] != '\0' && n > 0)
{
substr[j] = str[i];
i++;
j++;
n--;
}
substr[j] = '\0';
printf("\n The substring is: ");
puts(substr);
return 0;
}

13
Output:
Enter the main string: Hi there
Enter the position from which to start the substring: 1
Enter the length of the substring: 7
The substring is: i there

11. Inserting a String in Another String

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

#include <stdio.h>
int main()
{
char text[100], str[20], ins_text[100];
int i = 0, j = 0, k = 0, pos;
printf("\n Enter the main text : ");
gets(text);
printf("\n Enter the string to be inserted : ");
gets(str);
printf("\n Enter the position at which the string has to be inserted: ");
scanf("%d", &pos);
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++;
}
ins_text[j] = '\0';
printf("\n The new string is: ");
puts(ins_text);
return 0;
}

14
Output:
Enter the main text: How you?
Enter the string to be inserted: are
Enter the position at which the string has to be inserted: 6
The new string is: How are you?

12. Indexing

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

13. Deleting a string from the Main String

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


 We can write it as DELETE(text, position, length).
 For example, DELETE("ABCDXXXABCD", 4, 3) = "ABCDABCD"

Write a program to delete a substring from a text.

#include <stdio.h>
int main()
{
char text[200], str[20], new_text[200];
int i = 0, j = 0, k, n = 0, copy_loop = 0;
printf("\n Enter the main text: ");
gets(text);
printf("\n Enter the string to be deleted: ");
gets(str);
while (text[i] != '\0')
{
j = 0;
k = i;
while (text[k] == str[j] && str[j] != '\0')
{
k++;
j++;
}

if (str[j] == '\0')
{

15
copy_loop = k;
i++;
}
new_text[n] = text[copy_loop];
i++;
copy_loop++;
n++;
}
new_text[n] = '\0';
printf("\n The new string is: ");
puts(new_text);
return 0;
}
Output:
Enter the main text: Hello, how are you?
Enter the string to be deleted: , how are you?
The new string is: Hello

14. Replacing a Pattern with Another Pattern in a String

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

Write a program to replace a pattern with another pattern in a text.

#include <stdio.h>
int main()
{
char str[200], pat[20], 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("\n Enter the pattern to be replaced: ");
gets(pat);
printf("\n Enter the replacing pattern: ");
gets(rep_pat);
while(str[i] != '\0')
{
j = 0; k = i;
while(str[k] == pat[j] && pat[j] != '\0')
{

16
k++;
j++;
}

if(pat[j] == '\0')
{
copy_loop = 0;
while(rep_pat[rep_index] != '\0')
{
new_str[n] = rep_pat[rep_index];
rep_index++;
n++;
}
i = k;
}
else
{
new_str[n] = str[copy_loop];
i++;
copy_loop++;
n++;
}
}
new_str[n] = '\0';
printf("\n The new string is: ");
puts(new_str);
getch();
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?

17
Pointers
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.

Declaring Pointer Variables


 Pointer provides access to a variable by using the address of that variable.
 A pointer variable is therefore a variable that stores the address of another variable.
 The general syntax of declaring pointer variables can be given as below.
data_type *ptr_name;
Here, data_type: is the data type of the value that the pointer will point to. It can be int, float, char etc.
Asterisk (*): It tells the compiler that we are declaring a pointer variable.
pointer_variable_name: It is the name of the pointer variable.

Example:
1. int *ptr; // declares a pointer variable ptr of integer type.
2. float *temp; // declares a pointer variable temp of floating type.

Operators used with Pointers:


The two basic operators used with pointers are:
i. The Address of operator (&): By using the address of (&) operator, we can determine the address of the
variable.
ii. The Indirection operator (*): It gives the value stored at a particular address.

Example:
int a=3;
int *ptr;
ptr=&a;

18
ptr a
Memory layout:
65530 3
Address: 65530
 ‘ptr = &a’ copies the address of ‘a’ to the pointer variable ‘ptr’.

Example Program: Write a C program to print value and address of the variable using pointers.
#include<stdio.h> Output:
void main () The address of a=65530 and value of a=20
{
int a=20, *ptr;
ptr = &a; //ptr1 is a pointer to variable a
printf(“The address of a=%d and value of a=%d\n”,ptr,*ptr);
}
ptr1 a
Memory layout:
65530 20
Address: 65530

Initializing a Pointer Variable


 We can initialize the pointer variables by assigning the address of other variable to them. However these
variables must be declared in the program.

Syntax
data_type * ptr_name = address_of_variable;
where,
data_type:.It can be int, float, char etc.
Asterisk (*): It tells the compiler that we are declaring a pointer variable.
ptr_name: It is the name of the pointer variable.
address_of_variable: Itis the address of another variable.
Example:
int a;
int *ptr;
ptr=&a;
or
int a;
int *ptr=&a;
Both are equivalent.

 We can dereference a pointer, i.e., refer to the value of the variable to which it points, by using unary
'*' operator (also known as indirection operator) as *pnum, i.e., *pnum = 10, since 10 is value of x.
Therefore, * is equivalent to writing value at address. Look at the code below which shows the use of
pointer variable.
#include <stdio.h>
void main()
{
int num, *pnum;
pnum = &num;

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

Passing Arguments to Function Using Pointers

 Using call-by-value method, it is impossible to modify the actual parameters when you pass them to a
function. Furthermore, the incoming arguments to a function are treated as local variables in the function
and those local variables get a copy of the values passed from their calling function.
 Pointer provides a mechanism to modify data declared in one function using code written in another
function. In other words: If data is declared in func1() and we write code in func2() that modifies the data
in func1(), then we must pass the addresses of the variables to func2().
 The calling function sends the addresses of the variables and the called function declares those
incoming arguments as pointers. In order to modify the variables sent by the calling function, the called
function must dereference the pointers that were passed to it. Thus, passing pointers to a function avoids
the overhead of copying data from one function to another.
 Hence, to use pointers for passing arguments to a function, the programmer must do the following:
 Declare the function parameters as pointers.
 Use the referenced pointers in the function body.
 Pass the addresses as the actual argument when the function is called.

Let us write some programs that pass pointer variables as parameters to functions.

1. Write a C program to add two numbers using functions.


#include<stdio.h>

int add (int *a,int *b)


{
int sum;
sum = *a + *b;
return sum;
}

void main()
{
int a,b, res; Output:
printf(“Enter the values of a and b:”); Enter the values of a and b: 4 5
scanf(“%d%d”,&a,&b); result =9
res = add(&a,&b);
printf(“result =%d\n”, res);
}

20
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

3. Write a program using functions to find the biggest of three numbers.

#include <stdio.h>
int greater(int *a, int *b, int *c, int *large);
int main()
{
int num1, num2, num3, large;
printf("\n Enter the first number: ");
scanf("%d", &num1);
printf("\n Enter the second number: ");
scanf("%d", &num2);
printf("\n Enter the third number: ");
scanf("%d", &num3);
greater(&num1, &num2, &num3, &large);
return 0;
}
int greater(int *a, int *b, int *c, int *large)
{
if (*a > *b && *a > *c)
*large = *a;
else if (*b > *a && *b > *c)
*large = *b;
else
*large = *c;

21
printf("\n Largest number = %d", *large);
return 0;
}
Output:
Enter the first number: 1
Enter the second number: 7
Enter the third number: 9
Largest number = 9

4. Write a program to calculate area of a triangle.

#include <stdio.h>
void read(float *b, float *h);
void calculate_area(float *b, float *h, float *a);
int main()
{
float base, height, area;
read(&base, &height);
calculate_area(&base, &height, &area);
printf("\nArea of the triangle with base %.1f and height %.2f = %.2f", base, height, area);
return 0;
}
void read(float *b, float *h)
{
printf("\nEnter the base of the triangle: ");
scanf("%f", b);
printf("\nEnter the height of the triangle: ");
scanf("%f", h);
}
void calculate_area(float *b, float *h, float *a)
{
*a = 0.5 * (*b) * (*h);
}
Output:
Enter the base of the triangle: 10
Enter the height of the triangle: 5
Area of the triangle with base 10.0 and height 5.0 = 25.00

Pointers and Arrays

The concept of array is very much bound to the one of the pointers. An array occupies consecutive memory
locations. Consider Figure 14.2. For example, if we have an array declared as
int arr[] = {1, 2, 3, 4, 5};
then in memory it would be stored as shown in Figure 14.2.

22
 Array notation is a form of pointer notation.
 The name of the array is the starting address of the array in memory. It is also known as the base
address.
 Base address is the address of the first element in the array or the address of arr[0].
int *ptr;
ptr = &arr[0];
 Here, ptr is made to point to the first element of the array.
 Similarly, writing ptr=&arr[2], makes ptr to point to the third element of the array that has index 2.
 Figure 14.3 shows ptr pointing to the third element of the array.

 If pointer variable ptr holds the address of the first in the array, then the address of successive
elements can be calculated by writing ptr++.

 The printf() function will print the value 2 because after being incremented ptr points to the next
location.
 One point to note here is that if x is an integer variable, then x++ adds 1 to the value of x. But ptr is a
pointer variable, so when we write ptr + I, then adding i gives a pointer that points i elements further
along an array than the original pointer.
 Since ++ptr and ptr++ are both equivalent to ptr+i, incrementing a pointer using the unary ++
operator, increments the address it stores by the amount given by sizeof(type) where type is the data
type of the variable it points to.(2 for integer).
 For example, consider figure 14.4. If ptr originally points to arr[2], then ptr++ will point to the next
element arr[3]. This is shown in the figure 14.4

23
 If this had been a character array, every byte in the memory would have been used to store an
individual character. ptr++ would then add only 1 byte to the address of ptr.
 When using pointers, an expression like arr[i] is equivalent to writing *(arr+i).
 If arr is the array name, then the compiler implicitly takes
arr = &arr[0]
 To print the value of the third element of the array, we can straightway use the expression *(arr+2).
 Note that arr[i] = *(arr+i)
 Also, ptr = arr or ptr = &arr[0]
 We cannot write arr = ptr, because while ptr is a variable, arr is a constant. The location at which the
first element of arr will be stored cannot be changed once arr[] has been declared. Therefore, an array
name is often known to be a constant pointer.
Note: arr[i] , i[arr] , *(arr+i) , *(i+arr) gives same value.
 Let us look at the following code to understand the arrays and pointer relationship

 In C, we can add or substract an integer from a pointer to get a new pointer, pointing somewhere other
than the original position.
 C also permits addition and subtraction of two pointer variables. For example look at the code given
below.

24
 In the code, ptr1 and ptr2 are pointers pointing to the elements of the same array.
 We may subtract two pointers as long as they point to the same array.
 Here the output is 2 because there are two elements between ptr1 and ptr2.
 Both the pointers must point to the same array or one past the end of the array, otherwise this behaviour
cannot be defined.

[Link] a program to display an array of given numbers.

[Link] a program to read and display an array of n integers.

25
[Link] a program to find mean of n numbers using arrays.

____________________***********__________________

[Link] G
Assistant Professor
Dept. of CSE(AI&ML)
VVCE,Mysuru

26

You might also like