C Programming Course Ware

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Cour

seCode: CSC203
Cour
seTi
tl
e: COMPUTERPROGRAMMI
NGI
Cour
seUni
t: 3Uni
ts
Cour
seDurat
ion: 2HOURS

COURSEDETAI
LS

Cour
seWr
it
er/
Dev
eloper
: Prof.O.Folor
unso
Depar t
mentofComput erScience
Federal Uni versi
ty of
Agricul
ture Abeokuta,
Ogun
State,Niger
ia

Emai
l
: f
olor
unsoo@f
unaab.
edu.
ng

COURSECONTENT

WEEK10–11&12
 Str
ings.Def
ini
ngstruct
ures,accessi
ngstructuremembers.
 Whatarepointer
s,howtousepoi nter
s,pointerar
it
hmet
ic,et
c.
 Openingandclosi
ngsf i
le,r
eadingandwr i
tingafil
e

Lear
ningObj
ect
ives

 To f ami l
iari
ze t he st udent with basi
c concept
s of comput er
programmi nganddev el
opmentt ool
s.
 Topr esentt hesy ntaxandsemant i
csofthe“C”languageaswel las
dataty pesofferedbyt helanguage
 Toal low t hest udentst owr i
tethei
rownpr ogr
amsusi ngst andard
l
anguage i nfr
ast r
ucturer egardl
ess of t
he hardware or software
pl
atform.

Ref
erences/
Fur
therReadi
ng

CSC203
NOTE
1
MODULETI TLE: STRI NG, STRUCTUREANDPOI NTERS
Unit1: String
Introduct ion
Char act ersar et hef undament albui ldi
ngblocksofsour cepr ograms.Ev ery
progr am i scomposedofasequenceofchar act erst hat—whengr ouped
toget hermeani ngf ull
y —isi nt erpr eted by t he comput eras a ser ies of
i
nst ruct i
onsusedt oaccompl ishat ask.Apr ogram maycont ainchar act er
const ant s.A char acterconst anti s an integerv alue repr esented as a
char act eri nsi ngl equot es.Thev alueofachar act erconst anti st heint eger
valueoft hechar acteri nt hemachi ne’schar act erset .Forexampl e,' z'
represent st hei nt egerv alueofz, and' \
n'theintegerv alueofnewl ine.
Stringi saser i
esofchar act er st reat edasasi ngl
euni t.Ast ringmayi ncl ude
l
et t
er s,di gitsandv ariousspeci alchar acterssuchas+,- ,*,/and$.St ri
ng
l
iterals,orst r
ingconst ant s,i nC st ri
ngsar ewr itteni ndoubl equot at i
on
mar ksasf ollows:
Forexampl e:“ JohnQ.Doe”i sanamest r i
ng;“ 99999Mai nSt reet”isan
addr essst ringet c.
Ast r
ingi nCi sanar rayofchar act erstypeendi ngi nt henul lchar acter( '
\ 0'
).
Ast ringi saccessedv iaapoi nt ert ot hefi
rstcharact eri nthest r
ing.
Decl ar ationofAr rayofchart ype
Ast r
ingv ariabl ei sanyv alidCv ariablenameandi sal way sdecl aredasan
array .Thesy ntaxofdecl ar ationofast ri
ngv ari
ablei s:
charst ring-name[ si ze];
Thesi zedet ermi nest henumberofchar acterint hest ri
ngname.Exampl e:
Anar rayofchart y pet ost or et heabov estri
ngi stobedecl aredasf ol
lows:
charst r[8];

Anar rayofcharisalsocall
edasastringv ar
iable,si
nceitcanst
oreast r
ing
and itper mits us to change i
ts contents.I n contr
ast,a sequence of
characters
enclosedwi t
hinapairofdoublequot
esi scalledast ri
ngconst
ant.
Example:“Pr
ogram”isastri
ngconst ant.
Ini
ti
ali
z at
ionofArraysofcharType
CSC203
NOTE
2
Thesy ntaxofi niti
alizingast r
ingv ariablehast wov ariations:
Var iation1
charst r1[ 6]={‘ H’,‘
e’,‘l’
,‘
l’
, ‘
o’,‘\
0’};
Her e,st r1i sdecl aredt o beast ri
ngv ariablewi t
hsi zesi x.Itcanst ore
maxi mum si xchar act ers.Thei niti
alizer–l istconsi stsofcommasepar ated
char act erconst ant s.
Not et hatt henul lchar acter‘\ 0’i
scl earlyl i
st ed.Thi sis
requi redi nt hisv ari
at i
on.
Var iation2
charst r2[ 6]={“ Hello”} ;
Her e, st r2i sal sodecl aredt obeast ringv ar iableofsi zesi x.Itcanst ore
maxi mum si xchar act ersincl udingnul lchar acter.Thei nitiali
zer-l
istconsi sts
ofast r i
ngconst ant .Int hi
sv ari
at i
on,nul lchar acter‘\0’wi llbeaut omat icall
y
added
tot heendofst ringbyt hecompi ler.Inei theroft hesev ariati
ons,t hesi zeof
thechar act erar raycanbeski pped, inwhi chcase, t
hesiz eandt henumberof
char act er si nt he i niti
al i
zer-li
stwoul d be aut omat i
cal ly suppl i
ed by t he
compi ler.
Exampl e
charst r1[]={“ Hel l
o”} ;
Thesi zeofst r
1woul dbesi x,f i
v echar acterspl usonef ort henul l
char act er‘\ 0’.
charst r
2[]={‘ H’, ‘
e’,‘
l’,‘
l’
,‘o’,
‘\0’};
Thesi zeofst r2woul dbesi x,fivechar act ersplusonef ornull character

\ 0’.
Exampl e1
Pr ogr am t osor tal istofnumber s.
#incl ude<st dio.h>
#incl ude<coni o.h>
voi dmai n()
{
i
ntx[ 6], n,i, j
,tmp;
clrscr () ;
pr i
ntf( “ Ent ert heno.ofel ement s\ n”);
scanf( “%d” ,&n) ;
pr i
ntf( “ Ent er%dnumber s\ n” ,n)
;
for( i=0; i<n; i
++)
scanf (“%d” ,&x[ i]);
/*sor tingbegi ns* /
for( i=0; i<n; i
++)
for( j=i +1; j<n; j
++)
CSC203
NOTE
3
i
f(x[i]
>x[j
])
{
tmp=x[ i
];
x[i]=x[ j
];
x[j]=tmp;
}
/*sorti
ngends* /
pri
ntf(“sort
edli
st\n”
);
for(i
=0; i
<n;i
++)

pri
ntf(“%d”,
x[ i
])
;
getch();
}
I
nput–Out put
Entertheno.ofelement
s
5
Enter5number s
1030205040
Sortedli
st
1020304050

Exampl e2:
Cpr ogr am foraddi t
ionoftwomat r
ices.
#include<st dio.h>
#include<coni o.h>
#include<pr ocess.h>
voidmai n()
{
i
ntx[ 5][5]
,y[ 5][5]
,z[5][
5],m,n,p,q,i
,j
;
clr
scr() ;
printf(“Enternumberofr owsandcolumnsofmat r
ixx\
n”)
;
scanf( “%d%d” ,
&m, &n);
printf(“Enternumberofr owsandcolumnsofmat r
ixy\
n”)
;
scanf( “%d%d” ,
&p,&q);
i
f( (m !=P)| | (n!
=q))
{
printf(“Mat r
icesnotcompat ibl
eforaddit
ion\
n”)
;
exit(
1) ;
}
printf(“Entertheelement sofx\n”)
;
for(i=0; i
<m; i++)
CSC203
NOTE
4
for(
j=0;j
<n; j
++)
scanf(“
%d” ,&x[i
][
j]
);
pri
ntf(“
Entertheelementsofx\
n”)
;
for(
i=0;i
<p; i
++)
for(
j=0;j
<n; j
++)
scanf(“
%d” ,&y[i
][j
])
;
/*Summat ionbegins*/
for(
i=0;j
<m; i++)
for(
j=0;j
<n; j
++)

z[i
][j
]=x[i
][j
]+y[ i
][j
];
/*summat i
onends* /
pri
ntf(“
Sum mat ri
xz\ n);
for(i
=0;i
<m; i++)
{
for(j
=0;j
<n;j++)
pri
ntf(“
%d”,z[i][
j]
);
pri
ntf(“
\n”
);
}
getch()
;
}

Exampl e3
Wr it
eapr ogram f ormulti
pli
cati
onoft womat r
ices.
#include<st dio.h>
#include<coni o.h>
#include<pr ocess. h>
voidmai n()
{
i
ntx[ 5][5],
y[ 5][5],z[
5][5]
,m, n,p,q,I
,j
,k;
cl
rscr() ;
printf(“Enternumberofr owsandcol umnsofmat r
ixx\n”
);
scanf( “%d%d” ,&m, &n);
printf(“Enternumberofr owsandcol umnsofmat r
ixy\n”
);
scanf( %d%d” ,
&p, &q);
i
f( n!=p)
{
printf(“Mat r
icesnotcompat i
bleformulti
pli
cati
on\ n”
);
exit(1);
}
printf(“Entertheel ementsofx\ n”)
;
CSC203
NOTE
5
for(i
=0; i
<m; i++)
for(j
=0; j
<n;j++)
scanf(“%d” ,
&x[ i][
j])
;
pri
ntf(“Entertheel ement sofy\
n”)
;
for(i
=0; i
<p;i++)
for(j
=0; j
<q;j++)
scanf(“%d” ,
&x[ i][
j])
;
pri
ntf(“Entertheel ement sofy\
n”)
;
for(i
=0; i
<p;i++)
for(j
=0; j
<q;j++)
scanf(“%d” ,
&y[ i][
j])
;
/*Mul t
ipli
cationofmat r
icesofx7yends*
/
for(i
=0; i
<m; i++)
for(j
=0; j
<q;j++)
{z[ i
][j
]=0;
for(k=0;k<n; k++)
z[i][
j]+=x[ i][k]*y[ k][
j]
;
}
/*Mul t
ipli
cationofmat r
icesofx&yends*
/
pri
ntf(“ProductMat r
ixz\ n”)
;
for(i
=0; i
<m; i++)
{
for(j
=0; j
<q;j++)
pri
ntf(“%d”,z[i][
j])
;
pri
ntf(“\n”)
;
}
getch();
}

Exampl e4: Cprogram t


opr i
nttr
ansposeofamatr
ix.
[Thetransposeofamat rixisobtai
nedbyswit
chi
ngt her
owsandcol
umns
ofmat ri
x].
#incl
ude<st dio.
h>
#incl
ude<coni o.
h>
voidmai n()
{
i
nta[3][3],b[3][
3],
i,j
;
clr
scr() ;
print
f(“Entertheel
ement softhematri
x:\n”
);
for(i
=0; i
<3;i++)
for(j
=0; j
<3;j++)
CSC203
NOTE
6
scanf(“
%d” ,&a[i
][j
])
;
pri
ntf(“
givenmat ri
xis:\
n”)
;
for(
i=0;i
<3; i
++)
{
for(
j=0;j
<3; j
++)
pri
ntf(“
%d” ,a[
i][
j]
);
pri
ntf(“
\n”);
}
pri
ntf(“
transposeofgiv
enmatr
ixi
s:\
n”)
;

for( i
=0; i<3; i
++)
{
for( j
=0; j<3; j
++)
{
b[i][j]=a[ j][i
];
printf( “%d” ,b[
i][
j])
;
printf( “\n”);
}
}
get ch() ;
}
Exampl e5
Wr itea‘ C’ program tofindt heav er
agemarksof‘
n’st
udent
sof
fi
vesubj ectsforeachsubj ectusingar
ray
s.
Ans.
#include<st di
o.h>
voidmai n()
{
i
ntSno, S1, S2,
S3;
fl
oatt ot,av g;
charsname[ 10];
printf(“Ent erstudentno; ”)
;
scanf (“%d” ,&Sname) ;
printf(“Ent ersubject-1, sub-2, sub-3marks;
”)
;
scanf (“%d%d%d” ,&s1,&s2,&s3);
tot=S1+S2+S3;
avg=t ot/3;
printf(“total =%f”,tot)
;
printf(“Av erage=%f ”
,av g);
}
CSC203
NOTE
7
Exampl e6
Wr iteaCpr ogram t ocheckthegivenwordis‘Pal
i
ndr
ome’
ornot
.
Ans.
#incl ude<st di
o. h>
#incl ude<coni o.h>
voidmai n()
{
charst r[
80] ,r
ev [80];
i
ntk, i,j
, f
lag=0;
clrscr() ;
printf( “
Ent eranyst r
ing(max.80chars):\n”
);
get s( str)
;
for( i=0;st r
[i
]!
=‘ \0’;i
++);
for( j=i-
1; k=0;j>=0; j
—,k++)
rev[k]=st r[
j]
;
rev[k]=‘ \0’;
for( i=0;st r
[i
]!
=‘ \0’;i
++)
{
i
f( str [
i]
!=rev[i
])
{
fl
ag=1;
break;
}
}
i
f( flag==1) ;
printf( “
Gi venst ringisnotpal
indr
ome.\ n”
);
else
printf( “
Gi venst ringispal
indr
ome.\ n”
);
get ch() ;
}

Stri
ngHandlingFunctionsin‘C’
Toper for
m mani pul
ationsonstri
ngdata,ther
ear ebuil
t-
in-
funct
ion(l
i
brar
y
functi
on)Supportedby‘ c’
compil
er.Thestr
ingfunct
ionsare.
1.STRLEN( S1)
2.STRCMP( S1,S2)
3.STRCPY( S1,S2)
4.STRCAT( S1,S2)
1.STRLEN( S1):Thisfuncti
onisusedtoret
urnthelengthofthestri
ngname
S1,
Ex:S1=‘ MOID’
CSC203
NOTE
8
STRLEN( S1)=4
2.STRCMP( S1,S2):Thisisal i
brar
yfunctionusedtoperfor
m compar i
son
betweent wost ri
ngs.Thisf uncti
onreturnsav al
ue<zer
owhenst r
ingS1i s
l
esst hanS2.Thef uncti
onr et
urnav al
ue0whenS1=S2.Fi nal
lyt
hef uncti
on
ret
urnav alue>0whenS1>S2.
3.STRCPY( S1,S2):Thisisal ibr
aryfuncti
onusedt ocopythestr
ingS2t o
S1.
4.STRCAT( S1,S2) :Thisisal i
brar
yf unct
ionusedt oj
ointwostri
ngsone
aft
ertheot her.Thi
sf uncti
onconcatenatesstr
ingS2attheendofstri
ngS1.

Exampl e5:Cpr ogram toconcatenatet


hegi
vent
wost
ri
ngsandpr
intnew
string.
#incl ude<stdio.h>
#incl ude<coni o.h>
mai n()
{
chars1[ 10],s2[10],s3[
10],
i
nti ,j
,k;
printf(“Entert hefir
ststri
ng: \
n”)
;
scanf (
“%s,S”,s1);
printf(“Entert hesecondst r
ing:\n”
);
scanf (
“%s,S”,s2);
i=st rl
en(s1);
j=st rl
en(s2);
for( k=0,k<i,
k++)
s3[k]=s1[ k]
;
for( k=0,k<j,
k++)
s3[i+k]=s2[ k] ;
s3[i+j]=\ 0’;
printf(“Thenewst r
ingis\n”.
s3);
}

Uni
t2:Structur
esin‘C’
St
ruct
ure
2.
0Int
roduct i
on
2.
1Def i
nit
ionofStruct
ure
2.
2StructureDecl
arati
on
2.
3StructuresandArrays
CSC203
NOTE
9
2.
4St
ructurecont
ainsPoi
nters
2.
5Uni
ons
2.
6Defi
nit
ionofUnion
2.
7Di
ffer
encesbetweenStruct
ureandUni
on

Lear
ni ngObj ecti
ves
•Impor tanceofst ruct
ures
•Definiti
onofst ructur
e
•Implement ationofar r
aysinstr
uctur
es
•Definiti
onofUni on
•Uniondecl arati
on
•Dif
fer encesbetweenst ruct
uresandUnion

2.0Introduct ion
Arraysar eusef ult or efersepar atev ar i
abl eswhi char et hesamet y pe.i .e.
Homogeneousr efer r
edbyasi nglename.But ,wemayhav esi tuations
wher et herei s a need f or us t or efer to di ff
erent t ypes of dat a
(Heterogeneous)i nor dert oder i
v emeani ngfulinformat i
on.
Letusconsi dert hedet ailsofanempl oy eeofanor ganization.Hi sdet ails
i
ncludeempl oyer’snumber( Integert ype) ,empl oyee’sname( Char actert y pe)
,basi cpay(I ntegert y pe)andt otalsal ary(Fl oatdat at ype).Al lt hese
detail
sseem t obeofdi fferentdat at y pesandi fwegr oupt hem t oget her ,
they wi llr esulti n gi v i
ng usef uli nf or mation aboutempl oyee oft he
organizat i
on.
Inabov esai dsi t
uat ions,Cpr ov idesaspeci aldat at y
pescal ledSt r uctur e,
whichi shi ghlyhel pfultoor gani zedi fferentt ypesofv ari
abl esunderasi ngl e
name.
2.1Def initi
onofSt ructure
Agr oupofoneormor ev ariablesofdi ff erentdat at y
pesor ganizedt oget her
underasi nglenamei scal ledSt ructure.
Or
Acol lectionofhet erogeneous( dissimi lar)typesofdat agr oupedt oget her
underasi nglenamei scal ledaSt ructure.
Ast ructur ecanbedef i
nedt obeagr oupofl ogicall
yr elateddat ai tems,
whichmaybeofdi fferentt ypes,st or edi ncont iguousmemor yl ocat ions,
sharingacommonname, butdi stinguishedbyi tsmember s.
Henceast ructurecanbev iewedasahet erogeneoususer -defineddat at y pe.
Itcanbeusedt ocr eatev ar i
abl es,whi chcanbemani pulatedi nt hesame
wayasv ariablesofbui lt-
indat at ypes.I thel psbet teror gani zationand
managementofdat ainapr ogr am.
CSC203
NOTE
10
When a st r
uctureisdef i
nest he enti
re group’sref
erenced through the
str
uct urename.Thei ndivi
dualcomponent spr esentint hestructur
ear e
call
ed st ructure member s and those can be accessed and pr ocessed
separat ely.
2.2Str uctur eDeclarati
on
Thedecl ar ati
onofast ructur
especi f
iesthegroupingofv ari
ousdat ait
ems
i
ntoasi ngl eunitwithoutassigninganyr esourcestothem.Thesy ntaxfor
declaringast r
uctur
ei nCi sasfoll
ows:
str
uctSt ructure-Name
{
Dat aTy pemember -1;
Dat aTy pemember -2;
….….
Dat aTy pemember -n;
};

Thest ruct uredecl arationst artswitht hest ruct ureheader ,whichconsi st


sof
thekey wor d‘ str
uct ’followedbyat ag.Thet agser vesasast ruct ur
ename,
whi chcanbeusedf orcr eat i
ngst ruct urev ariabl es.Thei ndi
vidualmember s
oft hest ructur ear eencl osedbet weent hecur lybr acesandt heycanbeof
thesi mi l
arordi ssimi lardat at ypes.Thedat at ypeofeach v ari
ablei s
speci fi
edi nt heindi vidual memberdecl arations.
Exampl e:
Letusconsi deranempl oy eedat abaseconsi st i
ngofempl oy eenumber ,
name,andsal ar
y.Ast ructuredecl ar ati
ont ohol dt hisi
nformat i
oni sshown
below:
structempl oy ee
{
i
nteno;
charname[ 80] ;
fl
oatsal ;
};
The dat ai temsencl osed bet ween cur l
ybr acesi nthe abov e structure
decl arationar ecal ledst ructureelement sorst ruct uremember s.
Empl oyeei st henameoft hest ructur eandi scal ledst r
uctur
et ag.Not ethat,
some member s ofempl oy ee struct ure ar ei ntegert ype and some ar e
char acterar rayty pe.
Thei ndiv i
dualmember sofast ruct ur ecanbev ariabl
esofbui l
t–i ndat a
types( int,char ,floatet c.),pointer s,ar rays,orev enotherst r
uct ures.All
membernameswi thinapar ti
cularst ructuremustbedi ff
erent .Howev er
,
CSC203
NOTE
11
membernamesmaybet hesameast hoseofv ariablesdeclaredout sidet he
structure.Thei ndividualmember scannotbei nit
iali
zedi nsi
det hest ructure
declarat i
on.
Not e
Nor mal ly,
st r
uct uredecl arationsappearatt hebegi nningofthepr ogr am file,
beforeanyv ar i
ablesorf unct ionsaredeclared.
Theymayal soappearbef oret hemai n() ,alongwi t
hmacr odef init
ions,
suchas#def ine.
Insuchcases,t hedecl arat i
oni sglobalandcanbeusedbyot herfunct i
ons
aswel l
.
2.2.1St ructur eVar iables
Similart oot hert ypesofv ariabl
es,thestructur
edat at ypev ari
ablescanbe
declaredusi ngst r
uct uredef initi
on.
struct
{
introllno;
charname[ 20];
floatav er age;
a, b;
}

Int heabov est ruct


uredef i
nit
ion,aandbar esaidtobest r
uctur
et ype
variables.‘a’isast r
uctur
et ypevari
ablecontaini
ngrol
lno,nameav er
ageas
member s,whi char eofdiff
erentdatatypes.Simil
arl
y‘b’isal
soast ruct
ure
typev ariablewi ththesamemember sof‘
a‘.
2.2.2St ructureI ni
ti
ali
zati
on
Themember soft hest r
ucturecanbei nit
ial
izedli
keot hervar
iabl
es.This
canbedoneatt heti
meofdecl arat
ion.
Exampl e1
struct
{
intday ;
intmont h;
inty ear;
}
date={25, 06, 2012};
i
.e
date.day=25
date.mont h=06
date.y ear=2012
Exampl e2
CSC203
NOTE
12
str
uctaddress
{
charname[ 20];
chardesgn[ 10];
charplace[10];
};
i
.e
str
uctaddressmy -
add={‘ Sree’,
‘AKM’,
‘RREDDY’
);
i
.e
my -
add.name=‘ Sree’
my -
add.desgn=AKM
my -
add.place=RREDDY
Asseenabov e,theinit
ialvaluesforstr
uctur
emember smustbeencl osed
wit
hi napai rofcurlybraces.Thev al
uestobeassignedtomember smust
beplacedi nt hesameor derast heyarespeci
fi
edinst r
uct ur
edefinit
ion,
separat
edbycommas.I fsomeoft hemember softhest ructur
earenot
i
niti
ali
zed,
thent heccompi l
erautomati
call
yassi
gnsav al
ue‘zero’tot
hem.

Accessi ngofSt ructureMember s


Asseenear l
ier,thestructur
ecanbei ndiv
iduall
yidenti
fi
edusingtheperi
od
operator(.) .Af t
eri dent
ifi
cati
on,we can access t hem bymeans of
assi
gni ngsomev al
uest ot hem aswel lasobt ai
ningthestoredval
uesin
str
uctur emember s.Thef ol
lowingprogram il
lustr
atestheaccessi
ngofthe
str
uctur emember s.
Exampl e:Wr iteaCpr ogram,usingstructuredefini
ti
ontoaccepttheti
me
anddi splayit.
/*Pr ogr am t
oacceptt imeanddi spl
ayit*/
#include<st dio.h>
main()
{
str
uct
{
i
nthour , min;
fl
oatseconds;
}ti
me;
pri
ntf(“ Enterti
mei nHour s,minandSeconds\ n”);
scanf(“%d%d%f ”,
&time.hour ,&ti
me.mi n,&time.seconds);
pri
ntf(“Theaccept edt imei s%d%d%f“,t i
me.hour ,ti
me.mi n,ti
me.
CSC203
NOTE
13
seconds“ )
;
}
2.2.3Nest edSt ructures
Thest ructurei sgoingt ocer tai
nnumberofel ement s/ member sofdi f
fer
ent
datat ypes.I fthemember sofast ructureareofst r ucturedat atype,itcan
bet ermedasst r
ucturewi thst r
uctureornest edstruct ure.
Exampl e
struct
{
i
ntr oll
no;
charname[ 20];
fl
oatav gmar ks;
struct
{
i
ntday ,mon, year;
}dob’
}student ;
Intheabov edecl ar
at i
on, st
udenti sav ariabl
eofst ruct urety peconsist
ingof
themember snamel yrol
lno, name, avgmar ksandt hest ructurevari
abledob.
Thedobst ructureiswi thinanot herstructurestudentandt husstruct
ureis
nested.I nthist ypeofdef i
niti
ons,theel ement soft her equi rest
ructurecan
ber eferencedbyspeci fyingappr opriat
equal ifi
cat
ionst oi t
,usingtheperiod
oper ator(.).

Forexample,st
udent
.dob.dayr
efer
stot
heel
ementdayoft
hei
nner
str
uct
uredob.

Unit3: Pointerin‘
C’:VariableDefinit
ionsandIniti
alizati
on
Pointersar ev ari
ableswhosev aluesar ememor yaddr esses.Nor mally,a
vari
abledi rectlycontainsaspeci ficv al
ue.A poi nter,ontheot herhand,
containsanaddr essofav ar
iablet hatcontainsaspeci f
icv alue.Inthis
sense,av ariabl
enamedi r
ectl
yr eferencesav alue,andapoi nterindi
rectl
y
ref
erencesav al
ue( Fi
g.3.1).Referencingav al
uet hr oughapoi nteriscal
led
i
ndirection.

CSC203
NOTE
14
Fi
g.3.
1. Di
rect
lyandi
ndi
rect
lyr
efer
enci
ngav
ari
abl
e

Poi nt
ers,likeal lvariables,mustbedef inedbeforet heycanbeused.The
def i
niti
on
i
nt* countPtr,count;
specif i
esthatv ari
ablecount Ptrisoft ypei nt*(i
.e.,apointertoaninteger)
andi sr ead,“ countPtrisapoi ntertoint ”or“countPtrpointstoanobjectof
typei nt.
”Al so,thev ari
abl ecountisdef inedt obeani nt,notapoint
ert oan
i
nt .The*onl yappl i
est ocount Ptrint hedef i
nit
ion.When*i susedint his
manneri nadef i
nit
ion, i
tindi
catest hatthev ari
ablebeingdefinedi
sapoi nter
.
Poi nt
erscanbedef inedt opointtoobj ectsofanyt ype.

Pointers shoul d be i ni
tialized eit
her when t hey’
re def ined or i n an
assignmentst atement .Apoi ntermaybei ni
tiali
zedt oNULL, 0oranaddr ess.
A poi nterwi tht he v al
ue NULL poi ntsto not hing.NULL i sa sy mbolic
constantdef inedi nt he<st ddef .
h>header( andsev er
alot herheader s,such
as<st dio.
h>).I nit
iali
zingapoi nterto0i sequi valenttoi ni
tiali
zingapoi nter
toNULL,butNULLi sprefer red.When0i sassigned,i t
’sf i
rstconv er
tedt oa
pointeroftheappr opr i
atety pe.Thev alue0ist heonl yintegerv aluethatcan
beassi gneddi rectlytoapoi ntervari
able.
PointerOper ators
The&,oraddr essoper ator,isaunar yoper atort hatreturnst headdr essof
i
tsoper and.Forexampl e,assumi ngthedefinit
ions
inty=5;
int* yPtr;

thest
atement
yPtr=&y ;
assi
gnstheaddr essoft hevari
ableyt
opoint
ervari
abl
eyPtr
.Vari
abl
eyPtri
s
thensaidto“ pointto”y .Fi
gure3.2showsaschemat i
crepr
esent
ati
onof
memor yaf
terthepr ecedingassi
gnmenti
sexecut
ed.

CSC203
NOTE
15
Figur
e 3.
2.Graphi
calr
epr
esent
ati
on ofa poi
nterpoi
nti
ng t
o an i
nteger
vari
ablei
nmemory.

Theunar y*operator,commonlyrefer
redtoastheindi
rect
ionoper
atoror
deref
erenci
ngoperator,ret
urnst
hev al
ueoftheobj
ecttowhichi
tsoperand
(i
.e.
,apoint
er)poi
nts.Forexampl
e,thestat
ement

pri
ntf
("%d"
,*yPt
r);
pri
ntsthev al
ueofv ari
abl
ey ,namel
y5.Usi
ng*i
nthi
smanneri
scal
l
ed
deref
erenci
ngapointer
.

PointerExpr essionsandPoi nt
erAr i
thmet ic
Pointers ar e v ali
d oper ands i n ar i
thmet i
c expr essions, assi gnment
expressi onsandcompar i
sonexpr essi ons.Howev er,notal lt heoper ators
normal l
yusedi nt heseexpr essionsar ev ali
di nconj unctionwi t
hpoi nter
vari
ables.Thi ssect i
ondescr ibest heoper at
or sthatcanhav epoi ntersas
operands, andhowt heseoper atorsar eused.
Al imitedsetofar i
thmet icoper ationsmaybeper f
ormedonpoi nter s.A
pointermay
bei ncrement ed( ++)ordecr ement ed( --
),ani ntegermaybeaddedt oa
pointer( +or+=) ,ani ntegermaybesubt ractedf r
om apoi nter(-or- =)and
onepoi nt ermaybesubt ractedfrom anot her.
Assumet hatarr
ayi ntv [
5]hasbeendef inedandi tsf ir
stelementi satlocat ion
3000
i
nmemor y.Assumepoi ntervPtrhasbeeni ni
tial
izedt opoi ntt ov[0]—i.
e. ,the
val
ueofv Ptri
s3000.Fi gur e3.3il
lustratesthissituat i
onf oramachi newi th4-
byteinteger s.Var i
ablev Ptrcanbei niti
ali
zedt opoi nttoar rayvwi t
hei therof
thestat ement s

v
Ptr=v;
v
Ptr=&v[0]
;

CSC203
NOTE
16
Fi
gur
e3.
3.Ar
rayvandapoi
nterv
ari
abl
evPt
rthatpoi
ntst
ov.

Inconvent i
onalari
thmet i
c,3000+2y i
eldstheval
ue3002.Thi sisnormally
notthe
casewi thpoint
erarithmetic.Whenanintegeri
saddedt oorsubtr
actedfrom
apoi nt
er ,thepointerisnoti ncrementedordecrementedsi mplybyt hat
i
nteger,butbyt hatintegertimesthesizeoftheobjecttowhichthepointer
ref
ers.Thenumberofby tesdependsont heobj
ect
’sdatatype.Forexample,
thestatement

vPt r+=2;
wouldpr oduce3008( 3000+2*4) ,assumingani ntegeri sstor
edi n4by t
es
ofmemor y.Int hear r
ayv ,vPtrwouldnowpoi ntt ov [2]( Fig.3.4)
.Ifanint
eger
i
sst oredin2by tesofmemor y,t
hent heprecedi ngcal culationwouldresul
tin
memor ylocation3004( 3000+2*2) .Ifthearraywer eofadi f
fer
entdatatype,
theprecedi ngst atementwoul dincrementt hepoi nt erbyt wicethenumberof
bytesthatittakest ost oreanobjectoft hatdatat ype.
Whenper formi ngpoi nterar i
thmeticonachar acterar r
ay ,theresult
swillbe
consistentwithr egul
arar it
hmet i
c,becauseeachchar act eris1bytelong

Fi
gur
e3.
4.Thepoi
nterv
Ptraf
terpoi
nterar
it
hmet
ic.
CSC203
NOTE
17
IfvPt rhadbeeni ncrement edt o3016, whi chpoi ntst ov[
4],t
hest atement
vPt r-=4;
woul dsetv Ptrbackt o3000—t hebegi nningoft hear r
ay.I
fapoi nterisbeing
i
ncr ement edordecr ement edbyone,t hei ncrement( ++)anddecr ement( -
-)
oper atorscanbeused.Ei theroft hestat ement s
++v Ptr;
vPt r++;
i
ncr ement st hepoi ntertopoi nttot henextl ocationinthearray.Ei therofthe
statement s
-
-v Ptr;
vPt r-
-;
decr ement st hepoi nt ert
opoi nttot hepr ev i
ousel ementofthear ray .
Point erv ar i
ablesmaybesubt r
act edf rom oneanot her.Forexampl e,if
vPtrcont ainst hel ocat i
on3000,andv 2Ptrcont ainstheaddr ess3008,t he
statement
x=v 2Pt r-v Ptr;
woul dassi gnt oxt henumberofar rayel ement sfrom vPtrtov 2Ptr,i
nt hi
s
case2( not8) .Poi nterar i
thmet i
ci smeani ngl
essunl essper formedonan
array .Wecannotassumet hatt wov ar i
ablesoft hesamet ypear estored
cont i
guousl yi nmemor yunlesst hey’r
eadj acentel ementsofanar ray.

Apoi ntercanbeassi gnedt oanot herpoi nteri fbothhav et hesamet y pe.The


except i
ont ot hisr ul
ei sthepoi ntert ov oid( i
.e.,void* )
,whi chi sagener i
c
pointert hatcanr epresentanypoi ntertype.Al lpoi ntert ypescanbeassi gned
apoi ntert ov oid,andapoi ntert ov oidcanbeassi gnedapoi nterofanyt ype.
Inbot hcases, acastoper ati
oni snotr equired.
Apoi ntert ov oidcannotbeder eferenced.Consi dert his:Thecompi l
erknows
thatapoi ntert oi ntreferst o4by tesofmemor yonamachi newi th4- byte
i
nt egers,butapoi ntert ov oidsi mpl ycont ainsamemor yl ocati
onf oran
unknowndat at ype—t hepr eci senumberofby test owhi cht hepoi nterr ef ers
i
snotknownbyt hecompi ler.Thecompi l
ermustknow t hedat at ypet o
det er
mi net henumberofby test obeder eferencedf orapar t
icularpoi nter.
Poi nterscanbecompar edusi ngequal ityandr elationaloper at ors,but
suchcompar i
sonsar emeani nglessunl esst hepoi nterspoi ntt oelement sof
thesamear ray.Poi ntercompar i
sonscompar et headdr essesst oredi nt he
pointers.A compar i
sonoft wopoi nterspoi ntingt oel ement si nt hesame
arraycoul dshow,f orexampl e,thatonepoi nterpoi ntst oahi gher -
number ed
elementoft hear rayt hant heot herpoi nterdoes.Acommonuseofpoi nter
compar i
soni sdet erminingwhet herapoi nterisNULL.
CSC203
NOTE
18
Summar y
Point erVar i
abl eDef i
ni ti
onsandI nitializat i
on
•Apoi nt ercont ainsanaddr essofanot herv ari
abl et hatcont ainsav alue.I n
thi
s sense,a v ar iabl e name di r
ect lyr efer ences a v alue,and a poi nt er
i
ndi rect lyr eferencesav alue.
•Ref er enci ngav aluet hroughapoi nteriscal l
edi ndi r
ect ion.
•Poi nt erscanbedef i
nedt opoi nttoobj ect sofanyt ype.
•Poi nter s shoul d be i niti
al i
zed ei therwhen t hey ’re def ined ori n an
assignmentst atement .Apoi nt ermaybei nitiali
zedt oNULL, 0oranaddr ess.
Apoi nt erwi tht hev alueNULLpoi nt st onot hi ng.I nit
ializingapoi nterto0i s
equi valentt oi nitializingapoi nt ertoNULL, butNULLi spr eferred.Thev alue0
i
st heonl yi ntegerv aluet hatcanbeassi gneddi r
ect lytoapoi nterv ariable.
•NULLi sasy mbol icconst antdef inedi nt he<st ddef .h>header( andsev eral
otherheader s) .
Assi gnment
1.St at et heRel ationshi pbet weenPoi nt ersandAr ray s
2.a)Def i
neanar rayoft ypef loatcal lednumber swi th10el ement s,and
i
nitializet he el ement st ot hev alues0. 0,1. 1,2. 2,…,9. 9.Assumet he
symbol i
cconst antSI ZEhasbeendef inedas10.
b)Def ineapoi nt er, nPt r,thatpoi ntst oanobj ectoft ypef loat.
c)Pr intt heel ement sofar raynumber susi ngar raysubscr i
ptnot ation.Usea
forst atementandassumet hei ntegercont rolv ari
abl eihasbeendef i
ned.
Printeachnumberwi th1posi t
ionofpr eci siont other i
ghtoft hedeci mal
point .
d)Gi vet wosepar atest atement st hatassi gnt hest artingaddr essofar ray
number st othepoi nt erv ariabl enPt r.
e)Pr intt heel ement sofar raynumber susi ngpoi nt er/of f
setnot at i
onwi tht he
point ernPt r
.
f)Pr intt heel ement sofar raynumber susi ngpoi nt er/of f
setnot at i
onwi tht he
arraynameast hepoi nter.
g)Pr intt heel ement sofar r
aynumber sbysubscr ipt i
ngpoi nternPt r.
h)Ref ert o el ement4 ofar raynumber susi ng ar raysubscr i
ptnot ation,
point er/ offsetnot at i
onwi t
ht hear r aynameast hepoi nter,poi ntersubscr ipt
notat ionwi t
hnPt rand
point er/ offsetnot at ionwi thnPt r.
i
)Assumi ngt hatnPt rpoi ntst ot hebegi nni ngofar raynumber s,whataddr ess
i
sr ef erencedbynPt r+8?Whatv al
uei sst or edatt hatl ocat i
on?
j
)Assumi ngt hatnPt rpoi ntst onumber s[5] ,whataddr essi sr eferencedby
CSC203
NOTE
19
nPt
r–=4.Whati
sthev
aluest
oredatt
hatl
ocat
ion?

MODULETI TLE:OPENI NGANDCLOSI NGSFI LE,READI NGANDWRI TINGA


FILE
Fil
eOper at
ionsl i
kef open( )
,f close( )
, fpri
nt(),fscan( )
Thehel poft hesef unct i
onst heusercanopenaf il
ewitht hedat afile
speci ficat i
ons,cr eateandwr it
ei nfor mat i
oni nt ot hefil
eandcancl osethe
fi
le.Thef oll
owi ngar et hef il
epr ocessi ngr elatedf uncti
ons.
a.FI LEOPENf unctionf open( )
b.FI LECLOSEf unct i
onf cl
ose( )
c.FI LEI NPUTf unct ionsget c( )andf scanf (
)
d.FI LEOUTPUTf unct i
onsput c()andf printf
( )
a.Thef unctionf open( )
Thi sf unct i
oni susedt oopenadat af i
le.Mor eov er
,thi
sf uncti
onr eturnsa
point ert oaf il
e.Theuseoft hef unct ionis
filepoint er=f open(f i
lename, mode) ;
Wher ef ilepoi nterisapoi ntert oat y peFI LE, t
hef ilenameoft hef i
l
enamei s
nameoft hef il
ei nwhi chdat ai sst oredorr et
r i
eved( shouldbeencl osed
withi ndoubl equot es)andt hemodedenot est het ypeofoper ati
onst obe
per formedont hef il
e( thisal sot obeencl osedwi thindoublequot es).
But ,bef or emaki ngt hisassi gnment, t
hef ilepoi nterandf open( )shouldbe
decl aredasFI LEpoi ntert ypev ariablesasunder:
FI LE* f
ilepoi nt er,*fopen( );
Themodecanbeoneoft hef ol l
owi ngt ypes.
MODE MEANI NG
“r“- readf r
om t hef i
le
“w”- wr itetot hef i
le
“a”- appendaf il
ei enewdat ai saddedt ot heendoff il
e
“r+”- openanexi stingf i
lef orthesakeofupdat i
on.
“w+”- creat eanewf il
ef orreadi ngandwr it
ing
“a+”- openaf i
lef orappend, cr eateanewonei fthef i
l
edoesnotexi st
already
Exampl es
1.f ptr=f open( “rk.Dat ”,”w”);
2.f i
le=f open(“ sampl e.
dat ”,“r+” );

b.Thefuncti
onsfcl
ose(
)
Thefi
lesthatar
eopenedshoul
dbecl
osedaf
teral
lthedesi
redoper
ati
onsar
e
CSC203
NOTE
20
performedoni t. Thi
scanbeachi ev
edt hroughthisfunct
ion.
Theusageof
thi
sf uncti
onis:
fcl
ose(fi
lepointer);
Wher ef i
l
epointerisreturnedval
ueoft hefopen()functi
on.
Exampl es:
1.fclose(inputfi
le);
2.f close(
outputfi
le)
;

c.Thef uncti
onsget c()&f scanf(
)
1.getc()f unctions:thi
sf uncti
onisusedasi nglechar
act
erfr
om agivenfi
le
,whenev eraf i
leisrefer
encedbyaf i
lepointer
.Theusageofthisf
uncti
onis
get c(f
ilepointer)
;
2.fscanf() functi
on:Thi sf uncti
onisusedt or eadaformat
teddatafrom a
specif
iedf i
l
e.Thegener alusageofthisfuncti
oni s
fscanf( fptr,
“Cont r
ol St
ri
ng”,&li
st);where
f
ptr af
il
epoi
ntert
orecei
vef
ormat
teddat
a
Cont
rol
str
ing dat
aspeci
fi
cat
ionsl
i
st

List t
heli
stofv
ari
ablest
ober ead
fscaf(
inf
il
e,“%d%d,”&no,&marks)
;

d.Thefunct ionsput c()&fpr i


nt()
Example
1.putc()f unct i
on:Thi sf unctionisusedwr i
teasi nglecharacteri
ntoafi
l
e
ref
erencedbyt hef il
epoint er.Theusageoft hi
sfunct i
onis
putc( ch, f
il
epoi nter),
Where
ch-t hechar actertobewr it
ten
fi
lepoi nter-af ilepointertot hefil
ethatreceivesthecharacter
.
2.fpri
ntf( )function:t hi
sf unct i
oni susedtwr i
teaf ormatteddataintoa
giv
enf i
le.Thespeci fi
edinf ormationi swrit
tenont hespecifi
edf i
l
e.
Thegener al f
or m ofusagef orthisfuncti
oni s:
fprintf(fptr
,“Cont r
ol Stri
ng”,list
):
Where
Fpt
r f
il
epoi
ntert
owr
it
eaf
ormat
teddat
a
Cont
rol
str
ing dat
aspeci
fi
cat
ionsl
i
st
li
st- l
i
stofv
ari
abl
est
obewr
it
ten.
Exampl
e
CSC203
NOTE
21
f
pri
ntf(
outf
il
e,
”%d%f
”,basi
c,gr
oss)
;

Exerci
ses
01.Defi
neanAr ray.Explainone- dimensionalar
ray
02.Explai
nabouttwo-di mensional ar
ray?
03.Explai
nhowt odeclar e,i
niti
alizearrayofchartype.
04.Writ
eaCpr ogram tosortal istofnumber s.
05.Writ
eaCpr ogram foradditionoft womat ri
ces.
06.Writ
eapr ogram formul t
ipli
cat ionoftwomat ri
ces.
07.Writ
eapr ogram topr i
nttransposeofamat rix.
08.Explai
nStri
nghandl ingfunct i
onsi nC.
09.Wr i
teaCpr ogram t oconcat enat
et hegiventwost r
ingsandpr intnew
str
ing.
10.Explai
naboutFi l
eoper at
ionsl i
kefopen(),f
close()
,fpr
int()
,fscan().

CSC203
NOTE
22

You might also like