0% found this document useful (0 votes)
35 views11 pages

Book 10 Dec 2024

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)
35 views11 pages

Book 10 Dec 2024

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
You are on page 1/ 11

Pointers 9- 5

rvRES O f POINTERS
e m em or y space.
.1 ffft. rs save th . . .
v poiJlte po in te r 1s faster becaus e d ata is man·1 .. ,_
ut ed with the ad.dres
s, i.e. direct
1i} time with
ution . n. Pu
f) t'
ss to m em or y 1oc at io
.~1
, ,_e,ee . rs Th . the m em or y space
w ith th e poin • r assig
e, no ry is accessed efficiently te
• e po m te ns
,n
'fbt als .
.
,wJ and o releases 1t. d
e us ed w ith da ta st ructures. The eful fo r re pr es en tin g two-dimensional an
&Jinters ar rays.
y are us
/ii'! :ulti-diJnensional ar .
ts of an y type of ar ray ir respecti.ve of .1ts subscnpt range.
"re can access elemen
(~} e handling.
. pointers are used for fil
lly.
(11)
are us ed to al lo ca te m em or y dynamica
(rii) pointers

fJ pOINTERS AND A
DDRESS d
co m pu te r memo ry 1s • made b y the serru•-con uctor
ed
icat • The Byte
""r y of . mpl
the po in te r is .no t co s a ca paci ty to sto re a bit either O or 1.
~ tb"" . Each cell ha 9.2. .
:,.iJnOlogY- Memo?' co
m pn se s bi na ry cells em or y addr ess as shown in Figure
ue m
su ch byte has a uniq
1'35' unit of 8 bits. Every
Address
0
I
2
I
I
I
I
I
I

65535 .___ ___ ~

f IGURE <J.l
rved.
ory according to its data type is rese
riable of an y da ta type is declared, mem
. When a va
"tlample,
65550
65551
65552
65553
65554

11 <, llH 'I. { ~ al lo ca te d


in te ge r
rv ed for th e va ria bl es x. y an d c.. For an
y locations are rese cations 65S50 an d 65
551 ar e
~rlio.vn in Figurean9.d3,fomr chemaroracter variable one byte is reserved. The long addres.1 for xi s 65550 an
d
to hvo bytes each so on . Th e sta rti
or ey an d
d 65553 are used to st Figure 9.3 is 65554.
,; .,. "' -x . 111d 65S52 an eds only one byte and its Jocation shown in
'5ss.a.Illedmacte r ne
9-6 Computer Programming with C

9.4 POINTER DECLARATION


Pointer variables can be declared as follows.
Example:

c\..,( 1(. I\ TI ,\ ;
int *x;
float *f;
char *y;
(i)
-
In the first statement 'x, is an integer pointer and tells the compiler that it hold
8
dress of any integer variable. In the same way, 'f is a float pointer which stores th the ad.
of any float variable and 'y, is a character pointer that stores the address of any \address
variable. • • c aracter
(ii) The indirection operator(*) is also called the dereferencing operator. When a point 18.
erenced, the value at that address stored by the pointer is retrieved. er derer.
(iii) Normal variable provides direct access to their own values, whereas a pointer proVides. .
rect access to the values of the variable whose address it stores. 1.J1d1.

(iv) The indirection operator (*) is used in two distinct. ~ays with pointers, declaration
dereference. . . • ~
(v) "Yhen a pointer is declared, a star(*) indicates that it is a pointer and not a normal Variable.
• (~) When the pointer is dereferenced, the indirection operator indicates that the value at that
memory location stored in the pointer is to be accessed rather than the address itself.
(vii) Also note that * is the same operator that ·can be used as the multiplication operator. 1he
compiler knows which operator to call, based on the context.
(viii) ' & ' is the address operator and represents the address of the variable. %u is used with the
print f ( ) for printing the address of a variable. The address of any variable is a whole nwn-
ber. The operato.r ' & ' immediately preceding the variable returns the address of the variable.
In the below given example ' &' is immediately preceding the variable 'nurn' which pro- ,
vides the address of the variable.· . • • ·

r9.l Write a program to display the addr~ss of the ~ariable.

void main()
{
int mnn;
clrscr();
printf("Enter a Number=");
scanf("%d",&num);
printf("Value of num =%d\n",num);
printf("Address of num=%u\n",&num);
getche();
}

OUTPUT:
Enter a Number= 20
Value of num = 20
Address of num = 4066

' '
Coftlputer Programming with C

voi d ma in( )
(

int a,b ,•p a,• pb ;


clr scr ();
pri ntf ("E nte r Value of 'a' &
'b' • :") ;
sca nf( "ld %d",&a,&b);
pa=&a;
pb=&b;
pri ntf ("\ nV alu e of a=%d & b=
\d" ,a,b );
pri ntf ("\ nA ddr ess of a=l u", pa)
;
pri ntf ("\ nA ddr ess of b=l u", pb)
;
pri ntf ("\ n\n Ad dit ion of 'a'
& 'b' %d",*pa+*pb);
pa-=pb;
pri ntf ("\n •pa =% d *pb =ld ",* pa,
*pb );
pri ntf ("\ np a -=%u pb= iu" ,pa ,pb
);
pri ntf ("\ nA ddi tio n of *pa +*p
b : \d" ,*p a+* pb) ;
get che ();
}

OUTPUT:
En ter Va lue of 'a' & 'b' . ·:
8 4
Va lue of a=8 & b=4
Ad dre ss of a=4056
Ad dre ss of b=4058
Ad dit ion of 'a' & 'b' 12
*pa=4 *pb=4
pa=24350 pb=24350
.
Ad dit ion of *pa & *pb 8

Explanation:
In the above program, addresses of vari
ables 'a, and 'b' are assigned to pointers 'pa'
'pb'. The statement pa= pb; means the valu a:J
e of pointer 'pb' is assigned to pointer'pa',MW.
both the pointers have the same value
and they point to the same variable 'b: Hencc
addition is 8. ,tht

9.5 VOID POINTERS tic 1

Pointers can also be declared as void


types. Void pointers cannot be derefere
type conversion. This is because being nced without Clf!..l
void the compiler cannot determine the
the pointer points to. Though void poin size of the object'~
ter declaration is possible, void variable's
lowed. Thus, the declaration void p will declaration is 0~.,.
display an error message 'si ze of 'p' 5
or zer o' after compilation. i unkr.-•·
A pointer points to an existing entity. A
void pointer can point any type of variable 'th r«'
type casting. The size of a void pointer
displayed will be two. When a pointer is
declared
Wl .Ja~~
as~oetd.
bytes are allocated to it. Later using type
casting, a number of bytes can be allocated 0
Void variables cannot be declared because ~ de pb'C~
memory is not allocated to them and there
store the address. Therefore, void variable is no
s cannot serve the job actually they are mad
e for.
9-14 Computer Programming with C

When a poin. ter • · · 1· d it holds an unauthorized add


. is declared and not m1t1a tze , ress. lt •
manipulate such pointers. ~~
r .
9. l 2 Wnte a program to show the W1·td pointer and its output
ry d~
<~
\

void main ()
{
int k,*x ;
/* clrs cr (); * /
for(k=O;k<=3;k++)
prin tf(" %u" ~x[ k));
}

OUTPUT:
7272 24330 30559 27753

Explanation:
In this program, pointer xis not initialized. The succe
ssive locations are displayed.
(i) The forgetful assignment of a
new memory location in a pointer is called the pointe
lion. This happens when the wild pointer accesses the
location of the Wild point r~lt~.
pointer converts the legal pointer to the wild pointer. er. •1ie "',J
··lij
(ii) Sometimes the pointer attempts to acces
s the data that has no longer life.

9.7 CONSTANT POINTERS


The address of the constant pointer cannot be modified.
char * con st str= "Co nsta nt";
In the above example, it is not possible to modify the
address of the pointer st r. The following opera
lions will generate error messages.
str= 'san ' /* cann ot mod ify a con stan
t obj ect */
++s tr /* cann ot mod ify a con stan t obj
ect */
If pointer constant is pointing to a variable, we can
change the value of the actual variable but r.ct
through the constant pointer. The following valid and
invalid operations are given.
k=S /*p oss ible */ ,
*pm:5 /*in val id* /
p~++ /*p oss ible */
•p~++ /*in val id* /
*prn=S /*in val id* /
r9.13 \Vrite a program to declare a constant pointer and modify the value.
void main ()
(
int k=lO ;
int con st *pm=&k;
Po in t~ t- 15

ci rs cr () ;
. •;
)C..,40;
• •pm~so; in vk) al id o p er at io n
I it l t f( "k c% d" , ,•
pr

ExPltJnation: teger and . :ie type.


th e ab ov e pr og ra m , variable k is an in h th . pm is a constant pointer of the sm
In ot be changed throug tant pointer.
'Jhe va lu e· of k ca nn d th ro u;~ o: er pm , because pm is a cons ot pe rm it
e can be change only. Any constant entit
y cann
'Ibe value of a variabl its
any modification.

OPERATIONS WITH POINTERS


8A
RITHMETIC possibl I
d efix and
9. po in te r va ria bl es are also
Th e. nc re m en t, ecrement, pr ar e sh ow n
at io ns on . er at io ns
·thmetic op erns ca n be pe rf or m ed with the pomters. e effects of these op
MI.i:.... er at io
poSWA op
in Table 9•1. - - -
tic operation
r \B l f 'I. I : ~i!Jfe~.an~ ari~m_e Requir~d
Ad dr eu of tn
In iti al Opn-ations Byte.s
Address Operation
Data Type 4044 2
4048
4046 ++ l
in t i= 2 4054 4'052
4053 ++
ch ar c= 'x ' 4062 ◄054
4
4058 ++ 4
flo at f= 2. 2 4064 4056
4060 ++
lo ng 1= 2
ess is
of th e po in te r va riable for integers. th e addr
ob se rv e that, on incr
ement 40 48 because
!rom Table 9.1, we ca n. ad dr es s an d on in crement its value will be
. 4046 is th e original
~cremented by two, i.e tes. respec-
mtegers require tw o by
tes.
rs an d Jo ng in teg er s require l, 4 and 4 by
mbe in Table 9.1.
rs, floating po in t nu y locations are shown
. Similarly, characte crem en t th e m em or
in cr em en t and de variables. Display th e
m em or y
tively. After th e effect of cr em en t on po in ter
9.14 Write a pr og ra m to show the
effect of in in ci em en t of
r floating po in t nu m be rs before and after the
character and
locations of integer,
pointers.

\r01•
d m ai n ()
{

in t x ,* x l;
C ha r Y ,* yl ;
fl oa t z, * zl ;
C lr sc r( );
1Sft't:fll t kPN ti

9-16 Computer Programming with C

prin tf("E nter integ er, char acte r, float Valu es \nn) ;
scanf ("%d \c \f",& x,&y ,&z);
xl:::a&x;
yl=&y;
zl=&z;
print f{"A ddre ss of x = %u\n n,xl) ;
print f("A ddre ss of y = \u\n n,yl );
print f{"A ddre ss of z ~ \u\nN ,zl);
xl++ ;
yl++ ;
zl++ ;
prin tf("\ nAft er Incre ment in Poin ters\ nn);
print f{"\n Now Addr ess of x=% u\nn, xl);
print f("N ow Addr ess of y=% u\n", yl);
print f("N ow Addr ess of z=% u\nn ,zl);
prin tf("\ nSiz e of Integ er: %dn ,size of(x ));
prin tf("\ nSiz e of Char acter : %dn ,size of(y ));
prin tf("\ nSiz e of Floa t: %d" ,size of(z) );
}

OUTPUT:
Ente r integ er, char acte r, float Valu es
2 A 2.2
Addr ess of x = 4046
Addr ess of y c 4053
Addr ess of z =·4058
Afte r Incre ment in fain ters
Now Addr ess of x ~ 4048
Now Addr ess of y = 4054
Now Addr ess of z = 4062
Size of Inte ger: 2
Size of Char acter : 1
Size of Floa t: 4

Explanation:
Observe the output 4046 is the address of integer 'x', 4053 is the addre
ss of character Y.Di
4058 is the address of floating point number 'i. On the increment
of the pointer the~
of integer, character and float will be 4048, 4054 and 4062, respectively.
This is because apail-'
is incremented. if points to immediately next location of its type.
~ r •
9.15 Wnte a program to show the effect of increment and decrement
operators used as prefila.iid
, suffix with the pointer variable.

void main ()
{
int i, *ii;
puts ("En ter Valu e of i•");
scan f (''%dH, &i);
Pointers
9-17

.i.,.,,i; ,.
i crO; of i :a %u\n ",ii); J
l • ,, ...
f
,1,s f (''Add ress
of i C
%u\n ",++ ii); l ... \
ptifl~ f ("Add ress
of i = %u\n ",ii+ +);
pt.i.~t f ("Add ress
of i z:r. %u\n ",--i i);
pri f (''Add ress
of i = \u\n ",ii- -);
pri~~ f ( "Add ress ! I
pri f ( "Add ress of i = %u\n ",ii);
t:>
I .- II V

I print '
I

! ~l)'fl'V'f:
' vaiue of i= 8 o- / I

60
I t'fltet
.. ess o f 1. =
! ,'ddr
.

4 0 62
of i ==
40 r-( \
..........

,'ddress of i ==
iddress
4 0 62
O62
rJ -
" of i = 4
,'ddress
,'ddress of
i = 4 0 62
i = 4060'
rJ)
,'ddress Of

cfp 6 ~ ,:; r-J ~ ,


£xPlanation: 6 ~-;: ) ,'r .
{-, ~- . ~-- ·,, :
(i) The 1st prin t f () statement displays the address of i = 4 O6 O.
er variable 'ii'; so befor e
(il) The 2nd prin tf () statement prefix increment is done with point
printing it is incre mente d Hence, a pointer is an integer
type, and an integer requi res two
bytes in memory. Hence, the address of i = 4 0 6 2 .
address value is print ed
(ill) The 3rd prin t f ( ) statement is opposite of the 2nd. Here, the
printi ng incre ment ed
first and then it is incremented. Hence, it prints i=4 0 62 and after
,.
address becomes 4 0 6 4.
d first and then printe d.
(iv) In the 4th prin t f ( ) statement, the address of 'i ' is decremente
Hence the address of ' i ' is 4 0 6 2.
and then decre ment ed.
(v) In the 5th prin tf () statement, the address of' i' is printed first
On decrement, the address of ' i' becomes 4 0 6 0.
(vi) The last prin tf () statement prints the initial address of 'i'.

r9.l6 Write a program to perform different arithmetic operations using pointers.
Void main( )
{

int a=25 ,b:10 ,*p,* j;


P=&a;
j•&b;
clrsc r();
Prin tf("\ n Addi tion ~+b = %d", *p+b );
Ptint f("\n Subt racti on a-b = %d", *p-b ); If.~--
Prin tf("\ n Prod uct a*b m %d", *p** j);
Pointers •1 9

tf(" \n The
Poi nter s have the differen t add ress .•);
,r:i.n
p t! ("'\n Add
ress of a(j) •%u ",j) ;
ptj.! l f("\ n Add ress of
a(k )•\u ",k) ;
?tin t

I "11°•
poi nter s hav e the same add ress .
.rl'J'L J•·
ov• • ) .,. 4056
'f'IIO
111e s of a (J
, J.ddte s of a ( k) • 4056 _______________
_...J
dd.r:ess _ _ _ _ _ _ _ _ _ _ _ _
;.

. . . .
£,xplanatio~: th m the above program. The pointer van -
'fhe comparison betw een e two pomt~rs JS done
arison is made. Toe comparison of poin t·
able should _be _of e sam e d~~ typ~ while a comp
th
, in this program pointers , j, and , k
1

ers ,an test 1f eithe r address IS 1d~ntical or not Here


er variable 'a ' . Hence. they cont ain
are of integer data types and points to the same integ
the same address.

pOINTERS AN D ARRAYS
9,9
ts to the address of the first element
(i) Array name by itself is an address or pointer. It poin
together with their addresses can be dis-
(0th element of an array). The elements of the array
are always stored in contiguous mem ory
played by using array name itsel£ Array elements
locations.
. .1
Programs in this regard are explained below.
r9.18 Write a program to display elements of an
l
array. Start element counting fro~ instead of 0.

void main ()
(

int x[]= {2,4 ,6,8 ,10} ,k= l;


clrs cr() ;
whil e ( k<=S )
{
prin tf(~ %3d ",x[ k-l] );
., I
k++; . '
}

OUTPUT:
: fl
2 4 6 8 10 - ,;

Explanation:
element num ber is added in the base
Array element counting always starts from •o~ The
one is subtracted from base address of an
address and each element of an array is accessed. If
By adding one to its redu ced base a d ~
~r~ay, it points to the prior address of 0th elem ent
it 15 possible to start element coun
ting from 'I'.
Pointers 9-37

_,..,, th• following programs

~ gram to accept a string using charcter


- write aprid display it.
,. ;,iter a
3. Write a program to display all the element s of
an array using pointer.
pO ogram to calculate square and cube of 4. Write a program fD allocate memory for 10 int.egerS.
write a P'ed number using pointer of the vari- 5. Write a program to demonstrate the use of
i t~e entertalning entered numb er.
realloc () functions.
able con
ns
,.,..-•r th• followinWhyg questio
"
1.
What are P
ointers? are they importan t7

fxplain features of pointers .


• 13. How strings are stored in pointer variables? Is It
essential to declare length?

i 14. What is base address? How ls it accessed dif•


fxplain pointer of any data type that requires
3. ferently for one and two-dim ensiona l arrays.
four bytes.
Explain the use of(*) indirecti on operator. 15. Elaborate the address sto-red in the pointer and
4. the value at that address?
Explain the effect of ++ and - operators with
s. pointer of all data type. 16. Why element counting of arrays always starts
from'0'?
Wliat is an array of pointer? How is it declared?
6.
the relation between an array and a 17. Write a program to read and display a two-di-
7. Explain mensional array of 5 by 2 numbers. Reduce the
pointer.
base address of an array by one and start ele-
le?
! Why addition of two pointers is impossib ment counting from one.
9. Which are the possible arithmet ic operations 18. ExpJain tiny and large memory models.
with pointers? 19. What are the uses of mal loc {} and free (}
10. Explain comparison of two pointers. functions?
20. ExpJain the concept of dynamic memory
11. How one pointer points to another pointer?
allocation?
12, How will you recognize pointer to pointer? 21. Describe the vark>us function s used for memory
What does the number of '*'s indicate. aUocation.

V Whit ls/are the output/ s of the following programs?


1 char *p;
• Use pointer and display value and address of an
element p=c;
clrscr O;
\roict main () printf C'%sN, p~;
{
}
int num=lO ,*p;
P===&num; 3. Display two strings
clrscr () ; void r.iain O
Print£ ("%ct", *p); {
Printf( "%d" , num ) ,. char *c="In diaN;
Printf(" %u",& num); char *p =~Bha rat#;
Printf ("%u" , p ) ,. char *k;
9etche (); k=p;
i p=c;
Program . clrscr O:
\ro . on display of a string
pr1.ntf (""\s",p ~;
( l.d main o
print! C'tsN, k);
}
Char c(J•"In diaH;
9-38 Computer Programming with C

4. Use pointer and display values of an element by printf ("\n sum


various ways %d", d) ; Of " '
a
void main ()
{ 6. Addition, Substraction Mu1.
t1p1· .
& Modulus operation on P0 1cat1on I'\:..
I

int v=lO,•p; 1nters ' ..,.,,~


p=&v; void main() • "'
clrscr (); {
pr1ntf("v=%d v=ld v=\d",v,*p, int a=25,b=l0 ..
*(&v)); , P, *J.
p=&a; j=&b; '
clrscr();
printf("%d%d%d%ct\,,
5. Use pointers and display addition of two num- •
b,*p * *j,*p / *J •d ,ip~b,,►
bers with and without pointers 1
p \ ·1 I; •
void main () 7. Display numbers
{
int a=5,b=7,c,d,•ap,*bp; void main()
clrscr(); {
ap=&a; int x(}={l,2 I 3 I 4I 5I I)
6
bp=&b; c 1 rs c r ( ) ; ' , k~l •
c=a+b; while(k<=5)
d=•ap+*bp; {
printf("\n Sum of A & B pr intf ("%2d", k [X-l}).
I k••·I
ltd", C) ;

VI Find the bug/s In th• following programs

t. char sa [] ="How are you :•;


void main() char t, *f;f=&sa;clrscr();
{ pr1ntf (1\%s", f);
char *c;
float x=lO;
c=&x; 5.
printf("%d",*c); void main ()
{

I 2. int *t,x;t=&x;x=ll;
void main () *t++;
l clrscr();
{
·~ printf("%d",*t);
flo~t x=l0.25,*f;f=x;clrscr();
pr1ntf ("%g", *f);
6.
3.
void main()
void main ()
{
int t[]={l,2,3,4,S};
float x=l0.25,*t,•f; int *p, *q, •r;p=t;q=p[l]i
t=&x;
r=-p (2]; ..
f=&t;
clrscr () ; ,r1;
clrscr(); printf("%d \d %d'',•p, ♦q,
printf("%g",**f);

7.
4.
void main{)
void main ()
{
{
C

1-1'1

t
9.
void :""3i: -. ()
{
ir.t x=S;
ir.t •l:"r -,->.,- v . py;
x - ' .,
...
clrs ,.._.._ , ().
prir .~f( "ld~ ,px );

, .

You might also like