C Language - Chapter 4
C Language - Chapter 4
com
UNIT IV
4.0 INTRODUCTION
Pointers are one of the derived types in C. One of the powerful tool
and easy to use once they are mastered.
Some of the advantages of pointers are listed below:
A pointer enables us to access a variable that is defined outside
the function.
Pointers are more efficient in handling the data tables.
Pointers reduce the length and complexity of a program.
The use of a pointer array to character strings save data storage
space in memory.
The real power of C lies in the proper use of pointers.
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
64K
64 * 1K
64 * 1024 bytes
65536 bytes (locations)
Memory Locations
Address
..
..
..
..
32278
..
32279
..
65530
65531
65532
65534
65535
even bank
odd bank
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
We cannot change them, but we can only use them to store data
values.
For example, in the above memory organization, the addresses
ranging from 0 to 65535 are known as pointer constants.
Remember one thing, the address of a memory location is a
pointer constant and cannot be changed .
10
65510
Variable Name
Variable value
Variable address
Pointer Values
Memory is divided into number of storage cells called locations.
Out of these the addresses, the system assigns some addresses
of the memory locations to the variables.
These memory locations assigned to the variables by the system
are called pointer values.
For example, the address 65510 which is assigned to the
variable i is a pointer value.
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
(Pointing at constant)
int a[10];
&a
&(x+y)
(pointing at expressions)
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
In C , every variable must be declared before they are used. Since the
pointer variables contain address that belongs to a separate data type,
they must be declared as pointers before we use them.
The syntax for declaring a pointer variable is as follows,
data type
*ptr_name;
This tells the compiler three things about the variable ptr_name.
1. The asterisk(*) tells that the variable ptr_name is a pointer
variable.
2. ptr_name needs a memory location.
3. ptr_name points to a variable of type data type.
For example,
int *pi;
declares the variable p as a pointer variable that points to an integer
data type. Remember that the type int refers to the data type of the
variable being pointed by pi.
Initializing Pointers
Once a pointer variable has been declared, it can be made to
point to a variable using statement such as
ptr_name=&var;
Which cause ptr_name to point to var.Now ptr_name contains
the address of var. This is known as pointer initialization.
Before a pointer is initialized it should not be used.
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
*ptr_name
Example1
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
10
8342
pi
8342
8338
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Example2
The following code illustrates how to declare int ,char and float
pointers. Here we have declared three variables of type int, float and
char ,also three pointer variables points to int, float and char.
Remember here pf points to the value of type float but its type is
unsigned integer only.
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
pi
Garbage Value
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
ptr_ptr=&ptr_name;
This initialization tells the compiler that now ptr_ptr points to the
address of a pointer variable.
Accessing the element value,
**ptr_ptr;
It is equalent to *(*(&ptr_name));
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Example
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Casting pointers
When assigning a memory address of a variable of one type to a
pointer that points to another type it is best to use the cast operator to
indicate the cast is intentional (this will remove the warning).
Example:
int V = 101;
float *P = (float *) &V; /* Casts int address to float * */
Removes warning, but is still a somewhat unsafe thing to do.
Void Pointer
A pointer to void is a generic type that is not associated with a
reference type.
It is neither the address of a character nor an integer, nor a float
nor any other type.
It is compatible for assignment purposes only with all other
pointer types.
A pointer of any reference type can be assigned to a pointer to
void type.
A pointer to void type can be assigned to a pointer of any
reference type.
Certain library functions return void * results.
No cast is needed to assign an address to a void * or from a void
* to another pointer type.
Where as a pointer to void can not be deferenced unless it is
cast.
void *
void
Figure 4.2 pointer to void
Example:
int V = 101;
float f=98.45;
void *G = &V;
/* No warning */
printf (%d,*((int*)G)); /* Now it will display 101
float *P = G;
/* No warning, still not safe */
printf (%f,*((float*)G)); /* Now it will display 98.45
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Call by Reference
The
actual
parameters
are
changed
since
the
formal
parameters indirectly manipulate
the actual parameters
only
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
}
Example:
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
main
Code for main ()
display
f_ptr
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
f_ptr=function_name;
After this assignment we need to call the function, the syntax
associated with the function call is as follows,
(*f_ptr)(arguments);
This is another way of calling the function. There are no changes in the
declaration of the function body.
The below program simulates a simple calculator using function
pointers.
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
The name of the array num gets the base address. Thus by
writing *num we would be able to refer to the zeroth element of
the array, that is 1.
Then *num and *(num+0) both refer to the element 1.and
*(num+2) will refer 3.
When we have num[i] , the compiler internally converts it to
*(num+i).
In this light the following notations are same.
1
1000
2
1002
3
1004
4
1006
5
1008
elements
values
address
ptr
base address
Figure 4.4 Storage representation of array
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Example
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Note: Note that the array name num is a constant pointer points to
the base address, then the increment of its value is illegal, num++ is
invalid.
0
0
Rows 1
2
1
5
9
2
6
10
3
7
11
4
8
12
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Example
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
*(*(*(a+i) +j) +k) --> value stored at kth dimension ith row jth
column
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Example
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Example
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
The above program find the squares of the elements of the array .Here
we passed the name of the array as an argument to the function an in
the called function the formal argument is created and points to the
elements of the calling function argument array.
1. Downward flow
2. Upward flow
3. Bi-directional flow
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
4.10.1 CONSTANTS
The keyword for the constant type qualifier is const.
A constant object must be initialized when it is declared because
it cannot be changed later.
The syntax for declaring constant is
const type var_name = value;
Example,
const float pi=3.14;
Remember that, we cannot change the value of constant once it
is initialized.
A string constant can be declared as follows,
const char str[] =hello;
Pointers and Constants
Pointers can also be defined as constants. Depending on how they are
coded, however, three different variations can occur.
1. The pointer itself is a constant.
2. The object being pointed to is constant.
3. Both the pointer and its object are constants.
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
4.10.2 VOLATILE
The volatile qualifier tells the computer that an object may be
changed by entities other than this program. When the compiler owns
an object, it can store and handle it in any way necessary to optimize
the program. As an example, a C compiler may think that it is more
efficient to remove an object from RAM memory and put it int a
register.
4.10.3 RESTRICTED
The restrict qualifier, which is used only with pointers, indicates that
the pointer is only the initial way to access the deferenced data. It
provides more help to the compiler for optimization.
Let us at the following code:
int *ptr;
int i=0;
ptr=&i;
*ptr = *ptr+4;
*ptr = *ptr+5;
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
*ptr = *ptr+4;
*ptr = *ptr+5;
4.11 STRINGS IN C
A string is a sequence/array of characters.
C has no native string type; instead we use arrays of char.
A special character, called a null, is important because it is
the only way the functions that work with a string can know
where the string ends.
This may be written as \0 (zero not capital o). This is the only
character whose ASCII value is zero.
Depending on how arrays of characters are built, we may need
to add the null by hand, or the compiler may add it for us.
The following operations performed on character strings,
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
s[1]
s[2]
s[3]
s[4]
\0
1001
1002
1004
1005
1000
1003
s[5]
Address
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
\0 \0 \0
s[8] s[9]
\0
\0
200 201 202 203 204 205 206 207 208 209 --> Address
Figure 4.10 Partial Array Initialization
Initialization Without Size
If we omit the size of the array, but specify an initial set of characters,
the compiler will automatically determine the size of the array. This
way is referred as initialization without size.
char s[]={h,e,l,l,o};
In this declaration, even though we have not specified exact number of
characters to be used in array s, the array size will be set of the total
number of initial characters specified and appends the NULL
character.. Here, the compiler creates an array of 6 characters. The
array s is initialized as shown in Figure 4.11.
s[0]
s[1]
s[2]
s[3]
s[4]
\0
1001
1002
1004
1005
1000
1003
s[5]
Address
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
s[0]
s[1]
s[2]
s[3]
s[4]
\0
1001
1002
1004
1005
1000
1003
s[5]
Address
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
%ws
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
NOTE:
1. If the string to be printed is larger than the field width w, the
entire string will be printed.
2. If the string to be printed is smaller than the field width w, then
appropriate numbers of blank spaces are padded at the
beginning of the string so as to ensure that field width w is
reached.
Example:
#include<stdio.h>
void main ()
{
char s[]=RAMANANDA;
printf (%4s\n, s);
printf (%15s,s);
}
OUTPUT:
RAMANANDA
RAMANANDA
2. Precision Specifier
Syntax:
%w.ns
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char s []={R,A,M,A,N,A,N,D,A}:
clrscr();
printf(%0.2s\n,s);
OUTPUT:
printf(%9.4s\n,s);
RA
printf(%9.3s\n,s);
RAMA
printf(%3.5s,s);
RAM
getch();
RAMAN
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
NOTE:
The string is printed right justification by default.
If w > n, w columns are used to print first n characters .example
2nd and 3rd printf statements.
If w < n, minimum n columns are used to print first n
characters. Example, 1st and 4th printf statements.
3. Left justification
Syntax:
%-w.ns
Example:
#include<stdio.h>
#include<conio.h>
void main ()
{
char s []={R,A,M,A,N,A,N,D,A}:
clrscr();
printf (%-0.2s\n, s);
printf(%-9.4s\n,s);
printf(%-9.3s\n,s);
printf(%-3.5s,s);
getch();
}
OUTPUT:
RA
RAMA
RAM
RAMAN
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
gets (string_name);
The function accepts string from the keyboard. The string entered
includes the white spaces. The input will terminate only after pressing
<Enter Key>. Once the <Enter key > is pressed ,a null character(\0)
appended at the end of the string.
Advantage
It is capable of reading multiple words from the keyword.
Un-Formatted Output Function- puts ()
It is a library function available in <stdio.h>.
This a one parameter function and is invoked as under:
puts(str);
Where str is a string variable containing a string value.
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Example
#include <stdio.h>
#include <string.h>
main ()
{
char opening[255] = "And, the Oscar goes to... ";
char winner[255] = "American Beauty";
strcat (opening, winner);
When using strcat, be
printf ("%s", opening);
careful that you do not
getchar();
overrun the array size. For
}
example, do not append a
OUTPUT:
255 char word to opening.
And, the Oscar goes to... American Beauty
strcmp () function:
The strcmp function compares two strings identified by the arguments
and has the value 0 if they are equal. If they are not, it has the
numeric difference between the first non matching characters in the
strings. It takes the following form:
strcmp(str1,str2);
return value less than 0 means ''str1'' is less than ''str2'
return value 0 means ''str1'' is equal to ''str2'
return value greater than 0 means ''str1'' is greater than ''str2''
String1 and string2 may be string variables or string constants.
Example: strcmp(name1,name2);
strcmp(name1,John);
strcmp(their ,there);
Example: Password Protection
#include <stdio.h>
#include <string.h>
main ()
{
char password[255];
printf ("Enter password: ");
scanf ("%s", password);
while (strcmp (password, "bluemoon") != 0) {
printf ("Access Denied. Enter Password: ");
scanf ("%s", password); }
printf ("Welcome!");
getch();}
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
strcpy () function:
it takes the following form:
strcpy(string1,string2);
and assign the contents of string2 to string1.
String2 may be a character array variable or a string constant.
Example:
strcpy(city ,Delhi);
strcpy(city1,city2);
#include <stdio.h>
#include <string.h>
main ()
{
char word1[] = "And, the winner is....";
char word2[255];
strcpy (word2, word1);
Output:
printf ("%s", word2);
getch ();
And, the winner is....
}
strlen () function:
This function counts and returns the number of characters in a string.
It takes the form
n=strlen(string);
Where n is an integer variable, which receives the value of the length
of the string. The counting ends at the first null character.
Example:
#include<stdio.h>
#include<string.h>
void main()
{
char name[100]="Gore";
printf ("%d", strlen (name));
getch();
}
Output: 4
Note, however, that the
size of the array is 100
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
strrev () function
Reverses the contents of the string. It takes of the form
strrev(string);
Example:
#include<stdio.h>
#include<string.h>
void main()
{
char s[]=hello;
strrev(s);
puts(s);
getch();
}
OUTPUT:
olleh
strstr () function:
It is a two-parameter function that can be used to locate a sub-string
in a string. It takes the form:
strstr (s1, s2);
Example: strstr (s1,ABC);
The function strstr searches the string s1 to see whether the string s2
is contained in s1.If yes, the function returns the position of the first
occurrence of the sub-string. Otherwise, it returns a NULL pointer.
Example: if (strstr (s1, s2) ==NULL)
printf (substring not found);
else
printf (s2 is a substring of s1);
We also have the functions to determine the existence of a character
in a string.
Example: strchr (s1,m);
Will locate the first occurrence of the character m.
Example:
strrchr(s2,m);
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Copying
Function
Description
memcpy
memmove
strcpy
strncpy
Concatenation strcat
strncat
Comparison
memcmp
strcmp
strcoll
strncmp
strxfrm
memchr
strchr
Searching
Other
strcspn
strpbrk
strrchr
strspn
strstr
strtok
strrev
memset
strerror
strlen
Concatenate strings
Append n number of characters from
string
Compare two blocks of memory
Compare two strings
Compare two strings using locale
Compare first n characters of two
strings
Transform string using locale
Locate character in block of memory
Locate first occurrence of character in
string
Get span until character in string
Locate character in string
Locate last occurrence of character in
string
Get span of character set in string
Locate substring
Split string into tokens
reverse the content of the string
Fill block of memory
Get pointer to error message string
Get string length
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
h
1000
s [1]
s[2]
s[3]
s[4]
\0
1001
1002
1004
1005
1003
s[5]
Address
p
1000
Figure 4.13: Initializing using Character Pointer
We cannot assign a string to another. But, we can assign a char
pointer to another char pointer.
Example:
char *p1=hello;
char *p2;
p1=p2; //valid
printf (%s, p1); //will print hello
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
OUTPUT
hello
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
4000
5000
6000
7000
arr[0]
arr[1]
arr[2]
arr[3]
4000
8000
5000
8002
6000
8004
7000
8006
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
# include <stdio.h>
int main ()
{
char *name [] = {
"Illegal month",
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
};
}
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
Exercise Programs
1. The names of employees of an organization are stored in three
arrays, namely, first name, second name, and last name. Write
a program to concatenate the three parts into one string to be
called name.
2. Write a C program to read in an array of integers. Instead of
using subscripting, however, employ an integer pointer that
points to the elements currently being read in and which is
incremented each time.
3. Write a C program to find number of words, blank spaces,
special characters, digits and vowels of a given text using
pointers.
4. Write a C program using pointer for string comparison.
5. Write a C program to find out the presence of a substring in a
given string using pointers.
6. Write a C program to find the length of a given string using
pointers.
7. Write a program to reverse the strings stored in array of
pointers.
8. Write a program to find rank of a matrix using pointers.
9. Write a C program using pointers to read in an array of integers
and print its elements in reverse order.
10. Write a C program to arrange the given numbers in ascending
order using pointers.
11. Write a C program to find factorial of a given number using
pointers.
12. Write a C program to arrange the given names in alphabetical
order using pointers.
13. Write a C Program to compute the sum of all elements stored
in an array using pointers.
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
www.vtuworld.com
WWW.VTUWORLD.COM
www.vtuworld.com
ASSIGNMENT IV
1. a) Write short notes on pointer to void.
b) Write short notes on Address Arithmetic.
c) Explain pointer to pointer with an example.
2. a) How to use pointers as arguments in a function? Explain
through an example.
b) Write a C function using pointers to exchange the values
stored in two locations in the memory.
3. a) Explain how strings can be stored using a multidimensional
arrays?
b) What are the string in-built functions available? Write in detail
about each one of them with an example.
c) Write a C program to replace a particular word by another
word in a given string.
4. a) What is a pointer variable? How is a pointer variable different
from an ordinary variable.
b) Distinguish between address operator and dereferencing
operator.
c) Write a C Program to illustrate the use of indirection operator
* to access the value pointed by a pointer.
5. What is the purpose of array of pointers? illustrate with an
example.
6. a) Distinguish between array of pointers and pointer to array
with examples.
b) Explain pointer to function and function returning pointer
with example.
www.vtuworld.com
WWW.VTUWORLD.COM