0% found this document useful (0 votes)
63 views31 pages

Unit - 4 Notes

The document provides an overview of pointers in programming, detailing their declaration, initialization, and operations such as arithmetic and comparison. It explains how pointers store memory addresses of variables and discusses pointer arithmetic, including incrementing, decrementing, and pointer-to-pointer relationships. Additionally, it covers the use of pointers with arrays and the concept of pointer arrays.

Uploaded by

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

Unit - 4 Notes

The document provides an overview of pointers in programming, detailing their declaration, initialization, and operations such as arithmetic and comparison. It explains how pointers store memory addresses of variables and discusses pointer arithmetic, including incrementing, decrementing, and pointer-to-pointer relationships. Additionally, it covers the use of pointers with arrays and the concept of pointer arrays.

Uploaded by

nagas2820
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 31
} LA Pointers 7 pointer 15 0 Variable that Stor Ane adden {he omothes variable. (oo pistes & Variable ihote Value is the adver another variable , tes direct address of the memory Jo cation: at: Dato type * Variable name: at pagerick Gr) in called as indivect operators (ov) De reference apaatar . We ts also called an value at addxer operestor™ it ielrates Variable declared 7S pointer per Set ioe Tips , “a aK called reference The opevator oy ‘vavi able 5 fren bexnent (Cw) = ou the’ odds” oposartor’s ~ te ee 7d syplot sO Variable _narne ett P= wa Features’ b pointer Saver memory 2. Exeation time’ with — pom pulated with the oddvew tev direct green to memory Jocation - # The memory is accemed efficiently with the Pointer ie dignarnt cally smemory Ww alto cated ' od deallocted. eyo p : Y inte axe wed with ; data shruclure. space . tex ia faster. because data, 4s moni Declaration of pol Datatype *® pointer - name int *P yaviable that holds the is a pointer he s addves of anothey, integer vavial Pointer inttialtzation ¢ | Addie operator |. ned to initialize @ Pointer yariable, Syotort dota type * pty name = ie ex peston Exe int a, 7 (e210) : ‘ int *P5 7* declaration */ Pasa ys inital zation") Notes j ‘ (PE ™P3 [Here p is enbeger pointer vaxiable int PY Here. p is norrnal integer variable poimtey variable name a@ : P value of variables lo 65524 Addves of Location "6552 65522 | eal name | Variable value variable odaves| “65524 Accessi eosing a. a. Variable abigS 36 ita pirat 2 TO accers the value of the Variable, indirection operator C#) tired Cro accen the vartable'a’ Aug the pointer’ pi code it on =p prog PF include main () c ‘int *pty,7 5 Teus Ply auis Pantf( “value ob tt Jad", x pv); 5 e value of 1: u tog Finclude Gstdio. hz amain( ) ¢ “int 1 Y5 int *p 5” clysea( 5 eloz Pawts YurPS . | Print (s alee ob t= dd oy 5 Print (Sais atored ot addvers ‘Jolt ‘ otx)5 Prt? (“value of wring pty-nd4 “ BPs Print? (" addves op sing ply ena? /P)5 3 Prante C* Value oy in y= nd" ys ) ; * p= 255 ; Piatt Co now x eed . 3 5 Outputs value of 1 =10 x is Stored at addyew = $000 Value of x using pointer =10 addiow of x using pointer = 5000 Value oh rin GeO MW H = 25 Pointer to pointer ce Porntess ave ured to Stove the addrem of othed Vawtabler of similar datatype. Bul tf you want to Store the addyes of a pointer variable, then Yo Ggato need a pointer to Slose TL. Thus > when one pointer variable stoves the addyves of anothey pointes variable, i 7S Known a pointer , to Potntes vartable (8T Double pointer, taxe int «x# oe Datatype ** pointer rame) S mt x=107 pean: 3 Z a @-4Ps x P F ‘ [te] sp 1020 5 2030 to30 2030 & HF melude 2stdiowh> int main ¢ ) oC int Q=0; imt *P4; int ** p25 Plena; P2 =epLy Pritt (“Addie of a =nU\n", ya): peas Pritt (“Addven of PL= BAUD! wpa): Pott (adiee, o} P2 = hu\n\n", up2)> P¥ntt ("Value at the addvex stoxed by Paz hu\n"b?)- Arar e CNalueatthe actelvens Stored by PLe%din\n",* pa); pont f (value of pant eG nu" veluin o 5 5 output Addses of A= 3030 Addies of PL = 3032 Addres of P2 = 3034 Value at the oddior Stosed by p2 = 2686 3030 value at the adden Stoved by PL = 10 Volue of **p2 = 10 ¥EDD = hA\o", ** pr); yP2)3 Pointer Mnitinmetic Parte Anithenetic is the Set of valid avitometic Operations that Cn be performed on pointers - tence) there ave only a few operations that ave allased to perform on potters tn C donguage. The © Pointer avithenetic operation ave slightly dapgereot fom the ones that we generally ure for smothe matal ~ Calculation ! There operation, axe: V Increment /pecrement of, a pointer 2. Aecldition of integey to a pointer 3° sublaction of integey toa pointet 4. Subtracting tw pointes of the Some Type: 5. Comparison of potters. increment / pecrement of a pointer = : Increments Ik is a condition that’ alo Comes under addition . when a pointer is tore mented , TE incrementa by the number equal to the size of the data type for which itis a pointey. Ext If an integer pointer that Stores oddxex to00 is d incremented , then it will increment by 2 (size of an int), and the new addrey will point 4to l002. while ifoa float type pomted ts ticxernen tel then Tt uuill irevement by 2 (size of float) and the neo oddvex will be too2. Program? aA include 4Stdio. h> int matin ( ) ae Int numbey = 50 3 int *P5 P= 4 number; pantt ('Addtes of p variable ts ou\n" p); Ptts Pant (“Aled increment : Adve Of Pvariable is ‘hu\n", Pp Beluryn O05 opps Adds of P variable is 64300 Atel Tnevemnent 3 Addie of Pvariable is 64202 decrements It decrements by ‘the equal to the Size of the datatype for which ibis a pointey: Be Hon tntegey pomntey the stoves addres ooo tS decremented, then it sill decvement by 2 (size of 7 it) sand the new addres ail port to 948+ Popa? einclude int main () int number = 500 jt *P3 Pe nur bev 3 pants (SAddvow op P Variable isu”, P)3 P= P+35 Punt (“after odding 3: Addion of Parable is ‘da\n,y setuin 05 Jb: Addison of P variable ts 64800 After adding 3: Addie of P vanable is 64306 i sublrackion a Tobeger to 2_poi ) jlher a pointer Ts Subtracted wstlh an integer value, ype value PS frat wmnutliplied by the Size of the data type and then Subliacte fare the pointes similar to addition. ge where the pty i an integer pointer that Stores gov a8 aM addlwes . LP we Sublaact integes 5 FOO it wing the exprenion, ptr= pty-5 , then, the tonal addres Stored im the ptr will be "pty ©1000 ~Size of (int) *5 = 990. pnge* teivlude 2stdio.h> imt_ main) at numbey = 50; int *P 3 P= unumbers pantf (“addres of P variable 1s Yun”, P35 P= p-335 . Pact (* pjtersubbracteg 3:-Addhes of P vookable is Auie’, 95 return 05 Miss edt Styl Adve, of P vadable is 64300 He subhacting 3:-Addwos of P voeble IS 64294, 4. subtraction of tu poroters # The Subtraction of tw? pointers is possi ble only when they have the Same data ‘ype The vault is generated by caleulating the difperence oO the addyenes of the tre potters and cakcule “4 hous many bits of data it is according * . Pointer dota type.the Subtraction Oh tue pies betoeen the tov porn sets: | iver the increments 7 es 4 Say pivt (2davos + 000) Fox cexamyle : [uso Totegent pointers | and pty 2 (addies +1002) axe subtracted. the difhevence | bekocen addvener Is a bytes Since the Size of tat is 2 bytes , therefore the tecrement between ptyt ond phe2 is given by (2/2)=1 - | Pegrams dFinclude 2stdio-h> void mam ( ) | | € It mt T=100 ,4=200, Ky int * Pe wis ink quis K -g-p; Pantt (“pointer Subtraction: wu-Zu~ Zu”, pK) 5 Pointer subtraction: 210g _ Blog =p comparision Of Pointers 2 6 = ~~ : we @9 Compore lhe uso pointers by using the forapa tor operators imc. lle Con tn plernent Abies log wing all operators in C >, >=, 2 ,27,77, 12. yretums tue for the valed condition and slurs false the umaataified Cmdttion . sees pointet, Comparision Compares tuo porn tev adadvenes to which. they port ‘to ,twrtead of cormparing thet values. Ext ink | Pope deinclude int main( ) t Jt nue = 105 int * pid = pmum; int * pty 2 = enum, if (pty == ptr) Pratt (* Both the pointers points tothe came location 5 else 7 Pantt (* Both the pointers are not equal "); t2 si 2 Feturn 05 ck Both the pointers awe equal. P © Pointer ened Ary * Continuous memory Loabon axe allocated fer all the elemenls of the may by the cormpi ter. "The bare addiex is the Locton of the past element Cinder 0) a the array BF met als] = { to, 20, 30, 40, 50} elements alo] af} af2) L3J ala Value / 0 20,'|" 3d Go 50 Addros (000 loo2 loog (006 look 4 hore oddvex P= 2 aloJ -1000 Note? if p declared ax integer pointer , then the axtay £Q? Con be pointed by peas ) p=ualoj; res addres of another, Variable. * Every Value of {0 Combe acconed by using Pes Be P =ua [oJ = 1000 prt = Ralis =to02 pra = wale] =l00y p+3 =va[3] = 1006 pty =8al4) =lo08 Note® che Length of the data Aype = ‘Scale pactor? (Size of int = > bytes nothing but sale factor) jpddses of on element is calculated wring W's ade and the Scale factor oh data dy pe - i pt addves of al 3] = bare addiwa + (4 Scale paclor of int ) e = [000 + (3% 2) ~ 1000 + 6 = 1006 , Instead of uring away todening , ply Gan be used to acces antag - (pointer) ali] = 4 (Pti) => value of afi) PB addvens of another variable *P = value of anothes variable. Bug (P+3) giver value of aCa] Progr + deinclude’ £skdio. hy amoin ( ) { ! int al 5)5 int P15 PINLF (“enter 5 elernensts") + fot (i=0; 1255 itt) Scant ("44g ", walid)s Pepa [oJs ‘ Print# (“element of array ave"); fox (iso; f255 744) : Prien hd", (p+i))+, 2p Enter 5 elementS : 10 20 30 40 50 elementy of asray are t lo 20 30 4o 50. Jaros 4 pointers 2 Array ob pointer Th an away of the pointes Votiable, 1¥-’s abo known as pointer amauys. ov tt isa Collection of a addrones ov collection ob Ponte, Sqmloxt datatype * pointer_name Lanay-size] 3 Declaration ol Seston oy am ‘awed of pointers int *p[3] -y It vepyerenta an onrreny “of pointers that can hold 5 toteger element addrew * We can wake Sepavate pointer variables, hich con Point to the ditherent Yaluer or we Cam make one integer array of pointers that Com point fo all the values. Program x AFinclude 2Stdio-h> main C ) int a[3] = {10,20,30} 5 int * P[3],7 5 Aer (1-05 523 344) P Li) ome (iJ pantt (“elements of the away ave"), for (i205 1035 tee) print (sa \e "m eLtD); at # elements of the omay ove to 20 30 Pornt ev and Dove, ¢ Pormrey See 2? ancy Memory allocation for 2D anay mt af3)L3] = (42,3, 4,5, 6, 4/8/95 alejie] aCe) afeIe] allo}, apate - apaciy atisce} oCeIe) aI) afta) Ney eo eo eee 1 ls \a | 234 (1236 (238 Pho [242 ay 1246 124% 1250 ———_ —— 7 1$* row ond eo ado . int *P 7 assigning bore addres Taal =pafo] Lol 5 | ‘ , Col ° Pointe @) P-a ‘pointer is used to acces the elements OF. 20) one a follows OCI] LA] = * (P+ Cie column size +3) % Scale ject) alt) [2] =x (12344 (1e3 43% 2) = (1234+ (342) %2) = * (12344 (5) #2) (123440) we OC) oe feng = 6 Pagaam* aE imeclude estdio. hz main ( ) { : ‘int a[3)03] 1,55 Ae Paint # (enter element of 20 Bray ") > for Go; i235 itt) t for (5205 5235 j44) ¢ Sant (nd ua CCID); . 7 ; 5 | i P =ualol[o];, PROLF (element of 20 arrays ave ")s Fer (i=05 7235 14+) ¢ for (Jeo; j23 5 itt) ee ec Ped \ tm (Ptixgy i); Pat (“5 a enter element of 20 Prey 12°38 GS guy éq element of 20 array axe ~ UN > mw \ 4 aT: é aba he TTC C TTY o Struc buses: ghuctu 1K a Collection of difperent dace types yortblers grouped toge thet under a Stogle name + oe Sere kes joo abuck is used for creating Structure - Spoke * a Strackure_nare (tag) dactalype Hemi 5 dedaty pe mem 25) dhtaty pe member 05 4a Notes Structuve ends usith Semi -colon - = Structure variable declayation® gee at s whenever a Stucluve is defined then memory will not be allowed to member of Structure, ‘The memory usill be allocated tomembers Oy Stucluxe only when a sbuctuve wroviable declared» Syotax il syntor oe Stuck Stuck — neme ~ Suck’ Stru— name t { dedatype var 4, V2,----¥n datatype Vat ty) Vay ----Y9 d 2 ltatype vay, v2 ,~--¥9 == chs G 481 ,62- . Je Slruct Steu-name $1,524 . - 2 Student Ex: Ghuck studenk Zs . rt . : ink rao, MI, 5 ink w94,™2 m3 5 . chat name [20] - Chay name (20]-, e mg: 7 t Float Avg 5 toa : 5 s : Jsis25 Slack ShU-Name 81 182 | Accessing members of structure ¢ There ave 2 typa of operators | wed a4 Cy] member of Structure - 1 membey operator @ dot operator (-) “HE the Shucture variable is. an ordinay ox Normal Variable then we urer dot operator for accenteg the members of a Shucture, Ymbane Stucture_ name . Pennine Est Stuct Student S3 Ss tno = (05 2. Structure pointer operator: (—») peters § Struckuye name —y member operator 4 IP ye Stuck StudenbiKS ; S> ‘tno= {05 ' Structuye mibialezation le At the time of defining Structure Struct Stuclent { int ¥noj char name [20] 35 int Mats %, hse {10 | “tamu ") sao} . g. while declaring shuckive variable Separatly Shuck Student is int yn05 chay wame [20] 5 mt maryks ; bs gtwuct Student g= {20, "Somu",600 F 5” Ex dfinclude zstdio.h> oukput: main ( ) Student deta ave = Rollno = to Mame = Somu maks = 580 Tat Student mk 10; Char name [20] 4 int rnavks 5 Js = Lw,“somu’, 580 45 Printf Cin Stuclent detail ore“); Pantt (“m Rollno = %d “) 5-190) 5 . Pint#("\n name = +s, S-name ); Print (* tin wacaks = Zed" , Se mnecr ka) 5 j freay of Stuckures? ‘ sexipt Avroy elements, ave actered uring -the Sub rs accen: Variable Similarly ghucture member o%@ bey dot operator » The most Common we of Shuctuye fs anay of structure, 8x? Struct book b[t0] 10 elements in an array of Stucture ob type book. Wile ac Program to find total and weds a N Students wing array of Structure, AWinclude thinclude ZX conto.h> Strack Studest int Yollno, m4, m2,m3 5 oj Chay Sname[3o) ; float total, avg 5 je void main ( ) Stuct Student S Lio] 5 int yn7 Print (* enter the elements of 6”); Stanf (* Yo “un)j ' fox (iso; T2n 5i+4) ¢ Puintt (Senter the detarh of Student hd " i+!) > print Center rouno") + _ ccant ("ed") WSCA. “wllno) 5 pant? ( “enter Student rare’) ¢ / boom? ("%8" , cei]. Sname ) 3 palF (“student martes "); SME (Sd thd nd”, us EiDemma yw sCiJorma ¥SC1T-™3)7 SCiJ total = SCI]. m1 4+SCiJro2 +5CiJ3 5 sCil- AVI = SCI. total /33 pantt (“details of Student”) ; fot (720 3 T4n 5 44) pantt ("The delails of Student hd” 741 )3 Puintt ie rollno = Zed", SC] -wiine) 3 Pat# (“name 8" Ey Struck person Char nae [20]; Tok age; chav dobltoJ 5 uG ( Stuck Student t Struct perton int vollno 5 Floak mee #5 bs Fok main ) t Struck Student S15, bs Pante (* enter masks") > Sort (yeh ", wS1- Toho. Masks) > Pratt (“petarls of Student’); Pant ("ead” yStqmacre "D7, Paint Cage = hod "$1: tofo-age); Print (“do = 7-8 ’,St-inpp-DoB); Pratt (a0tin0 = Za", St-ingocteton) 3 Prot (“Detar of Student"); PRotf (*entey name os Seen (* 28") S1-info-name )>, Printt (* erste age “)s Stan (Med " Usd. into sage)s Pan bE(* enter nob") 5 Sont (*%S", ys vinjo.0oB) Paat-f (Senter sotinc") 5 Sant (*7d", Sl inp. vollno); « = F pointe* to Stucluress poe at 4 holds the addven of entive Structure - he member of the Chucture Gn be accened Using “paper operator called" 9”, peclgsastions Stuck sid x 5; Acc T . Pty — member name, : £y' S— Sno S — Sname Progxare ‘ four; ad “int Sn05 Char Snare (30); Float mars 33 main ) t Struct Std $5 Stuck Std «st 5 Print € (“enter Sno, Sname,reciks ")5 Seat (“Ad 155 TF" 45.Sn0,S-Smacre 7 HS» marks ) 5 SE=uS7 ‘ Print (nenbet ghd. a, St~'sno)5 Paint (“name = 7S *, St srame); Print (Sencar tes = oF J, 4 pdt 7 man 29) late a perem ‘from Copying one Stiucluve to anothey Shuclures chinclude stato. hy Main ( ] Struck employee t Chay name [io] 5 int age 5 Float Salary 5 ‘L Static stuck employee * {sanjay "30,5500 45, Struct exnploy fe e2r,e35, Strepy (2 -narne e2-age = e2. Salary 2 El mame) + el. ge = = esalary 5 POPES 8h semen (er Print t (Hey, 5 at one hd % f\o "hy Et-name, el. °F > esalary V5” Print # ("KS xq ZF YO" es came, e2-0g¢, €2-saley)); Pantt Chsnd4 hE\n" @3.names es. age €3- salary); outputs J €1 = Sanjay , 30,5500 | Sanjay 7 30, 5900 fele} es = Sanjay, 30, 5% Union | \ 7 h union TQ Collection of difpevent datatype d plements but all the smembesm Shaves the Same govege axea. syete* UNIO Union! tan nae BE union Wem cc “i G en : int a3 ae meme, cela 1 JP Chay ¢3 i ; y; dectatype memn 5 ae Declaration of union variable s — ee * union ikem 2, union itero { t jnt 05 intay Floct 63. Float b3 char ¢4 char ¢3 oe 5 union item t3 Glaytes Tnitiattzatron and | Acconing oe When an union 75 declared , Com pile allocaty memory ao to hold Largeit delatype members i the Weft Union is uted to Save memory - union is | eos When iL iA not neceraryy to awgn the | ™ . 4 Value, to all the members: of An'm ee Program® union Ten a inta; Ploat b3 Char ¢3 uy main( ) ¢ Union itern t3 t.azk fF t.b=20.5 5 tec sta’; Pant“ acted’, +-0)3 Pant t (*boye" 4.6); Paint # (“c= %c', bey 5 As you Gan See hee, the values of a ard b get Cowrupted and only voriable C pinta the expected verult This 14 becaue im union, the Memory 1S Shaved ameng clifjerent data types; Hence, theenly member whore value is currently stored will have the wnemory- ai In the akove example, value of the variable & was Stowed at Lert, hence the value of other variables is Lot. "gate betioren Amag wey yas homogenas data nae onoy of Sane ly pe woot be amsgned to me anothey clevectly. aa C ioat ye aey vA ombination a of elements mule dimentional array ave. possi ble. s. fo element 1) avvas Teferenced by Speciting aay name and its position TH the axray- exs avy [5] and Stuclure. stuclares > Ik Stores he berogenous data a. Strucluve of Sane “Yype con be assiqned: 3. Shuclure 1s a Combination of members. A noin care of shucture S+elernents ina stucluve UM vefevenced a& Stucture «membey name. Difference betiocen' Structure and union Stuctuve bstovex hetevogenious chia dmembers ave Shosed Sporately In memor J Aacation, 4 ’ *Ta stucluye alll caembers “© available. Unton lStosea he teroge Nous data a memberk axe Sloved in Aare ed Lo cation . 3: In onion oly one member 74 available. at atime. Less mem A Oceupies more memon| A, oceupher 4 it When Compared {to Union. when compared wilh P Struclures- ; + St of anion’ 1A the SrSize of the Shuckae tthe 87 + i forg ext total memory Space required Size of the . a by TA members. datatype senemloes ty the union, Dynamic memory allocation | Drmenis mney on 7 to Create +The Dynamic memory allocation 4 wed 2 memory, at vin time: Dynamic memory allocation allows a. program to Oban move Memory Space , while ranning os to” Beleare space shen no Space is vequived, c language does not have any dechnique allocate memory dynamically . There are four ltbsory -fanctions under“ Stdlib-h” © “ Alloc-hY Aor dynamic memory allocation. le malloc() ,2- Calloc( ) ,3-treel) , 4 Fealloc C ) Ie malloe( )é Alllocates vequarted Size of hyles and weluros a pointer Firat byte of allocates| Space + After creating memory it velar, bare addrew - - leis maily wefal to albate Memory to a Pointer vortatle during enecetion ttre. = [t allocats oly one block of memory. + The default Value iS garbage value . ” spe? pointer variable = (aype_cant®) malloc, (104 St2¢ of deta ‘a | pes Civ *) malloc (5% 2) g piv = Cint*) malloc C0) pike © popes to pind sum of 7 elements entered by ser TO perporrr {hia Pram, allocte memoy dynernically cing walloc 6) junction ahinclude Zstdio-h> dtinclucle ZStdlzb «h7 int main ) t int 1,7, ¥Pts, SuM=05 Pratt ("Enter number of elements ")5 Stont ("od “uy; PY = Cint *) malloc (w* sizeos (int))j FF (pty = = nurt) Print (“Error | mnemory not allocated.")+, exit (0) a Cremter elements of avvoy!")3 for(ie0y iz +41) . Notes free (rt) destroys the. allocated memory Sant (4 ", Plsti)s Sunt = * (phe) Prant# (sum =74") Sum) 5 feee(pety 5 weturn OF J : ary elemen, loc () ¢ Alivcates Space oe ° ¥ Qa pointe and ne aE r ‘ talizey to Zev? to memory. the defouk + UE allocates multiple blocks of one a initial value ts zero. "Wawa Contiguous memory allocation Syokaxs datatype *Pt4 = (dadalype *) Callac (mo-e}: blects y Size « ee, EX int «pe (int *) calloc (5,2) Program & 3 i] } | { atinclude Zsidio. h> dtinclude Zalloc.-h7 main( ) ¢ it T5 int ¥P= (int x) calloe(s,2)5 if (poe =Null) Pant (* memory is snot allocated"); else Print# (enter elernent)e fot (12057455 i+) Stam ("tod ", pti) 5 Print (“elements ore"); fot (4-05 145%,T4 +) Printé (“ed\t™, ¥ (+a), yi y elie § charye the size of pee viously allocated cee pis wed te modify siz Of allocaled memory ae realloc CP, byte Size) am € ree detnclude main ( ) { int xp =(int #) mallee (6) int 15 %P=105 (pty) =20; *p( ptr) = 305 realloc ( p ,10) 5 %(p+3) =U05 x(p+y) =50 fos (1-05 1255 i++) Printf ("Yod\t ", *CP+I))S eee (P) 3 3

You might also like