You are on page 1of 129
Contents Introduction 1 Declarations and Initialization 2 Control instructions 3 Expressions 4 Flcating Point Issues 5 Punctions 6 TheC Preprocessor 7 Pointers 8 More About Pointers 9 Amays 10 Strings 11 Structure, Unions and Emumerations 12 InpuvOupet 13 Command Line Arguments 14 Bitwise Operators 1S Subsleties of »pedef 16 ‘The const Phenomenon 17 Memory Allocation 18 Variable Number of Arguments 19 Complicated Dectarations 20. Library Functions wi " n 37 47 35 @ 31 107 129 141 157 169 119 189 227 237 Introduction “There is no dearth of good C programming books in the marke. However, I found that there is not much material which could help a CC programmer to test his prograrnming strengths, help improve his ‘confidence and inthe process hone his C skills. Hence this book: ‘This is not text book on C. Infact its ar from it. Itcontains a lot of questions sogregated topic-wise according to my perception ofthe language. Almost all the questions are real one's tsked by real people sttempiing to learn or program in C “There is no reason why you should read the questions in the same order as they appear inthis book. Youcan pick up any topic that you think you are good at (or poor at) and tr to test your skills on that topic. “There is a good chance that i you ae learning oF using C-and you hhave questions about C that area’ answered in any of the other books {you've checked, you would find them answered here. twould be 109 much to expect that you would find in this book answer to every ‘question you would have when you're programming in C. Ths is [because many ofthe questions that may come up in your program: ‘ming would have todo with your problem domain, whereas this book Concentrates only an the C language. Also it doesn't cover every aspect ofevery operating system under which Cis running, Problems specific to an operating systems, and general-purpose algorithms are properly discussed in books devoted to those topics. ‘At the end of each chapter you would find correct answers t0 the ‘Questions in that chapter. You would find some answers more laborate than others. At first sight this may seem unnecessary. However, Ihave done this to give you the complete picture rather than oversimplifying or leaving out important detail. Ihave tie to avoid the questions whose answers ate most obyious because te dea was not fo inerease the numberof questions, bt to presen questions which would force the readers to think tice before asivering, Thats tune withthe pit of C- be precise, brevity has its own importance So rll your sleeves and get on with the real questions. Good vc! Yashavant P. Kanetkar Nov., 1996 Chapter 1 Declarations and Initializations Qu What would be the ouput ofthe following program? 1 charfor 1,02 print (Sed ua ast), abe (2)) ] Q 2 What would be the output ofthe following program? inux=<0. rain) ints 20: rit (rex): Q 2 What would be the output ofthe f lowing program? main() ( int=40; vx =20: pri Wa" x); ) ae Qu Is the following statement «declaration ora definition? center int Qs ‘What would be the output ofthe following program? rman) { ext it; 120; print Seize ()) 4 Would vary from compiler to compiler Error, undefined powp Isittrcthata global variable may have several declarations, but only ‘one definition? Qu Is tare that function may have several declarations, bu only one Aefinition? Qs Inthe following program where is the variable « getting defined and, where is it petting declared? rin) i exemirta; Pit (St); ima=20; Q 19 ‘What would be the output of the following program? man) 4 tom nt a; i ("ask ) fta=29 ‘Test Your C'S A 20 Bo ©. Garbage value D. Error Q 10 ‘What's the difference between a defintion and declaration of a variable? Qu Ifthe definition ofan external variable occurs inthe source fle before its use ins parieuar function, then there is no need for an extern ‘declaration inthe function. Q iz ‘Suppose a program is divided into three files fl, f2 and 3, and a variable is defined in te file fT but usedin the files 2 and. Tn such, Aacase would we need the external declaration for the variables inthe files 2 and /3? Q 12 When we mention the prototype of a function are we defining the function or declaring i? Qiu ‘What’ the difference between the following declarations? _)6| Chapter 1: Declarations and Initilisations cextem int un); infu); Q us Why does the following program report ree fanction display) man ( spay) on) ( ) Q 16 What would be the onpat ofthe following program? nt ("ncitnanger’) ‘main() i extort fn (fost); ita a=tun(at¢) print (90a) ) intin aa) oat aa { ) retum (it) aa); 6 Test Your C Skills Bas Error Point out the error, if any, in the following program. stucteme char namel20; int age: ) some mare code may go hee“ (Chapier I: Declarations and Iitialisations z Q 18 If you are to share the variables or functions across several source files how would you ensure tha ll definitions and declarations are ‘consistent? Q 10 How would you rectify the error in the following program? 1 stuctemp }; 7 any cher protlypes may o here"! struct emp ( char namet2; intage: rit wks i", 9:nae, 8.298); ) Q 120 Global variables are available to all functions. Does there exist a ‘mechanism by way of which Lean make it available to some and not toothes _ es Test Your CStits (Chapter 1: Declarations and Initialisations Q 121 ‘A. 0.0.000000 What do you mean by translation uit? es D. None ofthe above Q 12 ‘What would be Q 1x Some books suggest that the following definitions should be he output ofthe following program? rn Beet ye ned nate Ishomen? ria) -(2.8 uaa (284 1222 pd a a As Settonpe ato) ) ‘AL Garbage values Q 125 a 933 @ 322 nou heme fay jn allowing progam, 32 Peau or ian, inte loins og rest) Q 1 ( rac) ‘What would be the output of the following program? ge) tat) mmain() a der ce 5 Pet ate sharma ; item: Q 1 hae b Boi: eosin, nt ling promen bs sat i ani hen i, nt lowing ro pir cet ea al) ac i 1 lo Test Your C Skills Chapter 1: Declarations and Initialisaions uy union a ais in char ch}; 20 40. Incase ofaconilict between local variables, the one which is 1 more local that gets the priority union a2 = 512; pain kd, zn) iin ) Q 17 ‘What do you mean by scope of a variable? What are the 4 ifferent Iypes of scopes that a variable can have? Q 12 What are the different types of linkages? Answers Au 42 A iw 20, Whenever there isa conflict between a local variable anda global, ‘variable itis the local variable which gets a priority Declaration A 15 D. extern int ‘isa declaration and nota definition, hence the eror. A 16 Yes Aw Yes A 18 extern int ais the declaration whereas int a A 19 A 2 ‘Test Your C Skills A 110 In the defintion ofa variable space is reserved for the variable and Some intial values given toi, whereas a declaration only identifies the type ofthe variable for function. Thus definition isthe place where the variable is created or assigned storage whereas declaration refers toplaces where te nature ofthe variables stated butno storage isallocated. Ai Yes A 1 We are declaring it. When the function alongwith the statements ‘belonging to it ae mentioned we are defining the function A iu Thereis no difference except forthe fact that the first one gives aint thatthe function fun() is probably in another source file. A 115 Here display(is called before itis defined. In sach cases the compiler assumes thatthe function display) is declared as (Chapter 1: Declarations and Iniialisations 13 int depay|) ‘Thats, an undeclared function is assumed to return an inrand accept ‘an unspecified number of arguments. Then when we define the Tunction the compiler findsthatitisretuming voidhencethecompiler reports the discrepancy. A 116 1D, The erroroceurs because we have mixed the ANSI prototype with K&R style of function definition ‘When we use ANSI protptype fora funetion and pass a flat tothe fanction it is promoted to a double, When the funeton accepts this double into afloat type mismatch occurs hence the eror ‘The remedy for this error could be to define the function as: intun oataa) { } Aun Because of the missing semicolon atthe end ofthe structure deol tation (the intervening comment further obscures it) the compiler believes that unt) would return something ofthe the type struct emp, Whereas in actuality itis attempting to return an in. This causes & Imismatch, hence an error results 1 Test Your C Skills A 18 ‘The bes arrangement sto place each definition in a relevant «file ‘Then, put an external declaration in a header file (file) and use include to bring inthe declaration wherever needed, The « file which contains the definition should also include the ‘header le, so that the compiler ean check thatthe definition matches the declaration, A 119 Declare the structure before the prototype off) A 120 'No, The only way this canbe achieved! to define the variable locally ‘in main) instead of defining it globally and then passing it to the functions which need it A 121 ‘A translation unit isa set of source files seen by the compiler and translated aa unit: generally one file, plus all header files men- tioned in include directives. A 122 , When an automatic array is partially initialised, the remaining aray elements ae initialised to 0. Chapter 1: Declarations and Intilisations 15 A 123 ‘A. When an automatic structure is partially intalised, theremaining elements of the structure are initalsed 00 A 194 Pre-ANSI C compilers had such a requirement. Compilers whic conform to ANSTC standard do not have such 2 requirement A 135 Here we are iniialising the function pointer p to the address of the function fun) But during tis initialisation the function has not been defined. Hence an eror. ‘Tocliminat this error add the prototype of the ju) before declara- tion ofp, as shown below: ‘ter int fun); orsimply inh); A 126 Ina pre-ANSI compiler union variable cannot be initialised. How: lever, ANSI C permits niilisation of first memeber ofthe union. _Test Your C Skills ‘Scope indicates the region over which the variable's declaration has tan effet. The four Kinds of scopes are: file, function, block and rottype, A 1298 There are three diferent types of linkages: external, internal and ‘none. Extemal linkage means global, non-static variables and fune- tions, infernal linkage means static variables and functions with fle Scope, and no linkage means local variabl Chapter 2 Control Instructions Q 21 What would be the ouput ofthe following program? main() C inti=a; switch (1) faut: print (oA mouse an elephant uly te case print (oBreeing rabbits sa hare raising xperoce’) beak pant ( break oxo print (“i pracice makes pact. then nobody's pare) lenis day’) Q 2 Point ou the error, if any in the for loop jae Test Your C Skills i inti=t forts) c prt (6a eo) W(i> 10) brook A. ‘Tecondionnthejor lop sams. ar renee aa €._Thofrloop aldo epaed we op pee Q 2s Point out the error, if any, inthe while loop. ( iti=1 while} rine) itli> 1) ca: ‘The condition inthe while loop is « must There should beat least a semicolon in the while). The while Toop should be replaced by afer loop. Noerror. poe ‘ontrol Instructions 1 Chapter 2: Q 2 Pint out the errr, if any, inthe while loop. rman() ( inti=1; while (<= 5 print 401) lia) (ete here Point out the error, if any in the following progracm main’) 1 inti=4,j=2, swich (7) ( case et "niTo ors human, to ergiveis aginst company pe break; case iit (you have nating ted, dont doithere") bre: Test Your Q 2% Point out he error, if any, in the following program. main) in sath (i ( case 1 print nRadoactve cals have 18 haves) case 1°2+4 Bote for ent ing wai”) Point out the error, ifany, inte following program. rmain() imta= 10: sich (a Print (Programmars never ce. They just gets nthe processing’): Skills Chapter 2: Control Instructions Q 28 Point out the error, if ny, in the following program. main) ( inti= switch (i) print |"Holo'); common forboth cases “pint "nits uit") break case? print (oMenay isthe root ofall eat) break } 1 Q 2 Rewrite the following st of staemens using conditional operators. bbla=1,0; H(a>10) b=20 Q 210 Point out the error, ifany. inthe following program. sain) fl ima=10, Test Your C Skills b= 200: pir (aac) } Q aun What would be the ousput ofthe following program hart] = "Parte musisars ae semiconductors; print a> 10 S505": st). ‘A. Part-time musicians are semiconductors B. _Part-time musicians are semiconductors ©. Enor D. None of the above Q 22 Q an Q 2 We want to test whether a value lies the range 2to4 or 507. Can wwe do this using a switch? _ Chapter 2: Control Instructions 23 Q 2s The way break is used to take the contol out of switch can continue be used fo take the control tothe beginning ofthe switl? 107b=20: dummy Note tha the following would not have worked a> 107D=20:5; A 20 ‘Walue required in function main(). The second assignment should be ‘written in parentheses as follows: ae570=100:(D=200) Chapter 2: Control Instructions 2s A 21 A A 212 Asfarasefficiency isconcemed there would hardly be any difference fatal. Ifthe cases ina switch are sparsely distributed the compiler may internally use the equivalent of an etre chain instcad of compact jump table. However, one should use switch where one can Mis definitely a cleaner way o program and certainly isnot any less efficient than the ielse chain, A 218 No. The cases in a switch must either have integer constants of constant expressions A 2u Yes, though ina way which would not be very practical ifthe ranges Ae bigger. The way is shown below. e Sich (2) ( case? case case 7 some statements broek case case 6: case 7 * some cer statements Chapter 3 break; Expressi Tens: pressions Q 21 What would be the output ofthe follow rman) fl Satc int a0) ed eS, la): What would be the output ofthe following program? print (i) ) 28 Q 33 “The expression onthe right han sie of && andl operators does not get evaluated if the left hand side determines the outcome. eTrvelFalse> Q v4 ‘What would be the output of the following program? ( iti=2; pind (ed Se 4,448); a4 43 44 ‘Output may vary from compiler fo compiler. Q 35 ‘What would be the output ofthe following program? pope ‘main() 1 imtx=10,y=20,25,1 print (rk) Chapter 3: Expressions 9 © Enor D. None ofthe above, Q x6 ‘Are the following wo statements same? ac207b=30:0 (ae=20)?b:c Q a7 Can you suggest ay other way of writing the following expression Such that 30 is used only once? ‘ Sook Q 38 How come thatthe C standard says tha the expression 0 is undefined, whereas, the expression [ates Raine Is perfectly legal Q 39 If afi] = i++ is undeined, then bythe = 7 by the same reason /= i + J should also be undefined. But ici no so. Why? 30 Q 30 Would te exesion p++ Q an Inthe fotlowing code in wh be disallowed by the compiler, order the functions would be called? aft (25, 14)°12( 124) +100) fA BRA The order may vary from compiler to compiler None ofthe above pore Inthe following code in which onder the functions would bec 11 (23,14)"2(124)) +180; 1.2.0 Bat The onder may vary from compiler to compiler None ofthe above Q 218 ‘What would be the output ofthe following program poe ini=-3) —_ ions 31 (Chapter 3: Expre mati 8K 44] ok “atid ed Md km) Q 2 ‘What would be the output ofthe following program? rran() print (MoS a, ' Q ss Pas i ipa Rating pop an) Simi: -3,j=2,k=0,m; Desa of ab ok Print (ins 6d a, 8,m) , Q a6 What would be the ouput ofthe following program? main) { inti=-2,) m=ssi8a 2 os Test Your C Skills Chapter 3: Expressions 33 ait (rsd 5d ea km) A } A 36 Answers. mAs oor ‘That's what some of the compilers would give. But some other ‘compiler may give a different answer. The reason is, when single ‘expression causes the same abject to he modified orto be modified and then inspected the behaviour is undefined A 32 4. Bu basicaly the behaviou® is undefined forthe same reason asin 311 shove, A 33 “True, For example if ais non-zero thea b will not be evaluated inthe expression all b A 34 1. The order of evaluation of the arguments to @ function call is, unspecified A 35 No A 37 (a.ce20)7 8b: 8c) =30 A 38 According fo the C standard an object's stored value can be modified only once (by evaluation of expression) between two sequence points. A sequence point accu = a the end of full expression (expression which isnot a sub-expression ina larger expression) + atthe &&, lland 7: operators = atafuncton cal (afterthe evaluation of all arguments, jst before the actual eal) Since in the frst expression ‘is geiting modified wwiee between two Sequence points the expression isundefined. Also, the secondexptes- sion is legal because a sequence point is occurring at and iis, Betting modified once before and once after this sequence pont A 39 The standard says that if an object is to get modified within an expression then all accesses ot within the same expression must be for computing the value to be stored in the abject. The expression ali] = i++ is disallowed because one ofthe accesses of tthe one in ‘fi has nothing to do withthe value that ends up being stored in In this case the compiter may not know whether the access should fore oF aftcr the ineremented value is stored. Since od way to define ithe standard declares it as undefined. i+ [isallowedbecause ‘isaccessed take pla there's Asagainet this tho expr to determines final value A 310 No, Because here even though the value ofp is accessed twice itis used to modify two diffe Abaaatt (C. Here the multiplication will happen before the addition, but in which order the Functions would be called is undefined A 32 . Here the multiplication will happen before the addition, but in ‘order the functions would be called is undefined. In an arith metic expression the parentheses tll the compiler which operands {20 with which operators but do not force the compiler to evaluate A 313 Chapter 3: Expressions Chapter 4 Floating Point issues Qu ‘Wat would be the output of the following program? ( foata=0.7 il(a ae int, 19 (38.0)); ‘Would the following prin) print the same valves for any value of a main) fala; ‘oan (t8a); prin (‘Se/arata)> print (%t 3" a); Q 46 ‘We want to round off x, afloat, to an int value, The corect way to 050 would be A. y=(imty(x+05); int (x +05); (int) +05; CGint) (int) x05 ) Qa Which error are you Tikely 10 get when you run the following rogram? aa stuctem, i char namef20 fat sal; = “ Tes Your uly (hater 4 lang Pon wes 4 i iat shel yu doo ea he cota 3.14 fa? bec npato flied jie dhe) Qun ‘a a nao bt) ! What shoud yu do eae cmt 3.14 long double? A. Susp pointer cnreion Ls Bloating po oma one a ©. Chmote scan stacey Sng cnt esl ne tus Yat wuld e upto folowing program? 48 & What causes the errorin problem 4.7 above to aceur and how would you rectify the error in the above program? Q 49 ‘Which ate the three different types of real datatypes availabe in and what are the format specifiers ase for for therm? Q 410 By default any real number ested as float Adouble Tong double spends upon the memory model that you are using Q an poe> mi) it W350 c,sizao (3,14) szeo( 3.14), sizeof (2.141) ); } 444 4 Garbage value Garbage value 4310 Exor Q a4 The binary equivalent of 5375 is pae> A. to1,101110111 B. toro © 01011 B. None ofthe above Q 15 How floats are sored in binary foum? : il 2 — Test Your C Skills Chapter 4: Floaiing Point Issues a Q 46 Answers A float occupies 4 bytes. Ifthe hexadecimal equivalent of each of As these bytes is A,B, CandD, then whe this lat is storedin memory these byes get sored inthe order i A aBcD B DCBA A #2 oxABCD D. OxDCBA B Q an A 43 If the binary equivalent of 5.375 in normalised form i 0100 0000, D 1010 1100 0900 0000 0000 000, what would be the ouput ofthe following program? Py man) { fosta=5375; char’p; ini; =(cher*) a: for(i=0sie=3;H4) pr ("402 (unsigned cha) pf) 40Ac 0000 04CA 0000 (0000 Ac40, 0000CA 04 poe 'No, ince we have not included the header file “math.h” A 45 No. For example, for 1.7 the vo prin wool! print diferent A ts A A 47 “ Test Your C Skills A 48 What causes the lating point Formats not linked” error to occur? ‘When the compiler encounters a reference tothe address of alot, itseis flag to have the linker link in the leating point emulaior. A ‘oating point emulators used 1o manipulate oating poin: numbers, in runtime library functions like sce) and ao). There ate some ceases in which the reference to the float isa bit obscure and the ‘compiler does not detect the need forthe emulator. These situations usually occur during the intial stages of program development. Normally, once the program is fully developed, the ‘emlator wll be used in sucha fashion thatthe compilercanaceurate~ ly determine when to link inthe emulator ‘To force linking of the floating point emulator into an application, {just include the following function in your program vod LinkFoat (void) ( foata=0, b= Ba; cause emulator tobe inked) 2°; / suppress wating -var roused") ) ‘There is no need to call this Func A 49 from your program. oat byes Sf ouble Sbyes “lf long double 10bytes LE A 410 zz Chapter 4: Floating Point Issues 4s B A au Use314t A 4122 Use 3.141 A 413 e A 41 B A 415 Floating-point numbers are represented in IEEE format. The IEEE, forma for floating point storage uses a sign bit, a mantissa and an exponent for representing the power of 2. The sign bit denotes the Sign ofthe number: a 0 represents a postive value and a1 denotes a negative value. The mantssaisrepresentedinbinaryafterconverting itto its normalised form, The normalised form results ia a mantissa ‘hose most significant digit is always 1. The IEEE format takes !dvantage of this by not storing tis bit at al. The exponent isan Jeger sored in unsigned binary format after adding a positive Integer bias. This ensures that the stored exponent is always positive. The value ofthe bias is 127 for loars and 1023 for doubles, A A 416 Aan Chapter 5 Functions Q 61 What would be the output ofthe following program? rman() c inta,b; mig (1235 = au (123) print ("Sed a,b); ' i) aint = 0 ing it{nl-o) reun(s) # ‘est Your C Skills “Chapter 5: Functions Q «2 What error would the following function give on compilation? Qu ‘Point out the error in the following code {int itd) mah) ( ina 4223; uma ) ) ‘A. Missing parentheses in return statement rn) B. The function shouldbe defined as int a, ib J © Redecaration of @ p(w"); D. None ofthe above Qs. 65 There isa mistake inthe following code. Add statement in it to int out the error if any, in the following function. “ma ) man) { in; inta; b=1(29); ant 10,314); | ab}; int, ) (ta) {(inta, fatto) t 82207 retam{ 10): tum (20); ratum ( (ot) 2a + bb ) ) Q ie A function cannot be defined inside another fuction, 30 Test Your C Stills Q 57 Will the following functions work? H(itayinb) ( retum (2(20)); ‘linta) i 4 Q ss ‘What are the following vo notations of defining functions common: ly known as: ret (a*a): in (int a, oats) ( soma cade ) intt(a.b) inca: foatb; i 1 Q 59 ‘Ina function two rium statements should never occur. some code */ ‘Chapter 5: Functions 3 Q 510 “Ina function two return statements should never occur successively, “cTrvelFalse> Q sn “In C all functions except main() can be called recursively. TruelFalse> 512 Usually recursion works slower than loops. 53 ttc that oo many recursive calls may result into stack overflow”? es!No> but ‘many times the following program would print Jamboree"? ) “ain Infinite numberof times 32767 times (65535 times 5: Functions 3B 52. Test Your C Skills D. Till the stack doesn’t overflow A 56 Answers: A 51 mA 5.7 612 A 52 58 ic ‘The first one is known as ANSI notation and the second. known as ighan and Ritchie or simply, K & R notation. A 53 59 Adi the following function prototype i main fea (int oat); A 54 5.10 Inspite of dofining the Function () as returning void, the program is ‘eying to collect the value retuned by f) in the variable a A 55 bu Ise. Any function including main() can be called recursively. ‘return stalement cannot be used as shown with the conditional ‘operators. Instead the following statement may be uscd ee retum (a> 20710:20); 3 Test Your C Skills A 53 Yes A 518 Chapter 6 The C Preprocessor Qu ‘Ifthe file tobe included doesn’t exist, the preprocessor flashes an error message. Q «2 "The preprocessor can trap simple errors like missing declarations, nested comments or mismatch of braces. Q 63 ‘What would be the ouput of the following program? ‘eatne SOR x") “mai() C inta,b=3; a=80R(b+2); Print (wea) A 2 Bo 56 ‘Test Your C Skills © Bror D. Garbage value Q s4 How would you define the SQR macroin6.3 above such that itgives the result oF a as 25, Q os Wat oil te he oupu fhe following program? ‘eine CUBED) x") main() 1 inta,b=9; 2= CUBE (++): int “ned ea, ) Q v6 Indicate what would the SWAP macro be expanded toon preprocess: ing, Would the code compile? ‘deine SWAP(2, 0,0) (21 vt) aabbe1:) Intx=10,y=20; SWAP (x,y nt) Print (Sd x,y) ) Qa "In which line of the following program an error would be reported? “FLOATPTR a, Chapter 6: The C Preprocessor ‘How would you modify the SWAP macro in 6.6 above such that tis able to exchange two integers. Q vs What isthe imitation ofthe SWAP macro of 6.7 above? Q «9 4, deine CRCUMIA)(3.14° RR); 2 main) a ( 4 5 8 7 628) a Print ( Nnotbedygoak 8 H Q 610 ‘What isthe typeof the variable din the following declaration? ‘eine LOATPTR Rat * 38 ‘ess Your € Skills, Q on Tsitnecessary thatthe header files should have extension? Q oe ‘What do the header files usualy contain? Q a Would it result into an error if header file is included twice? : Q 614 ‘How can a header file ensure that it doesn’t get included more than Q os (nincasion, where arth header es searched for? Q 4 Would the following rypeder work? ‘ypodel nude |; print (sea); at would be the output of the following program? "pri MESS"); ld the following program print the message infinite number of ls? in INFINTELOOP while (1) oo ‘Test Your C Skills main) ( INFINTELOOP. Print (“Grey hare) 1 Q 620 ‘What would be the ouput of the following program? ‘éetne MAX(,b) (a>b7.a:b) mman|) ( ionx; x= MAX (942,247); ail Q 621 ‘What would be the output ofthe fllowing prograrn? fedeine PRINT in) print (dl * it) main) ‘What would be the output ofthe following program? er 6: The C Preprocessor 61 “tetine PRINT int) print (ot = td int) How would you modify the macro of 6.22 such that it ouputs: x=2 y=3.2=4 eit Tips Traps") 625 fine the macro DEBUG such tat the following program outputs; @ Test Your € Shits Chapter 6: The C Preprocessor 63 ot PAINT(a.b.¢); DEBUG (x,%d); ers DEBUG (2,9), DEBUG (eh, %e}: 61 , True Q 528 | 62 | ‘What would be the output ofthe following program? Aetna ste False Aelia Yate) ee ‘datne oper mutily A 63 mai) i har ‘qperame = Xs (ope); Bint ( "6s" opemame 'B. Because, on preprocessing the expression becomes d= (3 +2* 243) A 64 Adon SOR(o) (4 * 2) A 65 Q 2 Write the macro PRINT for the following program such that it outputs: 27 6. Though some compilers may give thi asthe answer, according fo the ANSI C standard the expression b++ * b++ * b++ is undefined. Refer Chapter 3 for more details on this A 66 (int: n4225 2o=3 by be13); a. ‘Test Your C Skills ‘This code won't compile since declaration of reannot occur within parentheses A 67 ‘ene SWAP(a,b,c) ct;t=a,a=b,b=t; A 68 cannot swap pointers. For example, the following code would not compile. amines A 69 Line number 7, whereas the culprit is really the semicolon in line ‘number 1. On expansion line 7 becomes if((3.14 * 1.0 * 1.0); 628 ) Hence the error. A 610 {float an nota pointer to afloat, since on expansion the declaration becomes: Neat ',b; Chapter 6: The C Preprocessor 65 A 61 No, However, traditionally they have been given a .h extension to dontify them as something different than the program files A 612 Preprocessor directives like Alene, structure, union and enum dee- Iazations, pedef declarations, global variable declarations and ex- {eral function declarations, You should not wrtethe actual code i. function bodies) or global variable definition (hat is defining oF fntialising instance) in header file. The include directive should be used pullin header files, not other files, A 613 ‘Yes, unless the header file has taken care to ensure that i already included it doesn’t get included again. A ou “All dectarations mastbe written inthe manner shown below. Assume ‘that the name ofthe header file is FUNCS H. hanes’! ‘indo|_FUNCS ‘iaine_FUNCS (ral declarations would go here" Henat Now if wo include this file twice as shown below, it would get included only once Chapter 6: The C Preprocessor or fa Test Your C Skills ‘include “goto.” A 620 ects po0e mreb|) c 9 sae code") , A 621 A 615 234 included using <> the files get scarched inthe predefined (can be A 62 hanged) include path. included withthe "syntax in aon 69 Bea ‘hepredefined include path thefles ako get searched inthe curent Bes siretory (usualy the directory fom which you invoked the com pile). A 622 | eine PRINT it) pnt int "= it) A 616 ‘main() ( Na Bi pis wine eg itso PRNT(y): A 617 PRINT (2); , No. Even though the defi in this case (NOTE being undefined) and the if block doesn't go for compilation ertors in it are not permitted, A 68 Mess A 619 Yes ‘The rule is if the parameter name is preceded by a # in the macro ‘expansion, the combination (of # and parameter) will be expanded, Jintoa quoted string with the parameter replaced by the actual argu ‘ment. This can be combined with string concatenation to print the ‘output desired in our program. On expansion the macro becomes pant (x= Sx) “The two strings get concatenated, so the effect is iret x= 98x) Test Your C Skills A 624 ‘Yes. The output would be TipsTraps. In fact this esulthas been used, in 6.23 above. A 625 ‘ine DEBUG vat) print (“DEBUG var A 626 et var) ‘multiply Here two operations are being caried out expansion and stringing, ‘Xsir) macro expands its argument, and then str) stingies A 627 ‘ne PRINT( vat, var, va) pint ("Wart "= "ard" = ed ‘vara"= "6d" vat var, va) Chapter 7 Pointers Qu "Can you combine he following {Wo statements into one? harp; ‘p= malo (100); Q 2 Can you spt te followin statement ino vo statement? harfor ‘or = (char far *) OxBB000000L; Q a3 Ae the expressions "pire and ++%ptr same? Q 4 ‘Can you write another expression which does the same job as 4p? 0. Test Your C Sills Q is ‘What would be the equivalent pointer expression for refering the same element as aff J0AI007 Q ve ‘What would be the ourpr of the following program? ~ intan{}=( 12, 19,14 15,16): it "nthe sia a), seo (ar), sia an]}): ) Qa ‘What would be the output of the following program assuming that ‘the array begins at location 1002? ‘main() intIs1=( 1.2.34, 5.8.7.8, 910,14,12 bh it int ou Su lO} 1, "(D+ 1),°(" (2-40) 41)) ) Chapter 7: Pointers 78 ‘What would be the output ofthe following program assuming that the array begins at location 1002? int a2]914 = Se ra Sao Bee 3, 0 Prin retusa Se", "a 79 the following program how would you print 50 using p? int al}= (10, 20,90, 40,50); char"p char"); Test Your C Skills Q 710 werent Qi Inthe following program adda statement in the function fi) such that address ofa gets stored inj. ran) i ing; voifun int , fecal von (int) { in: ‘add staoment hee *F it Q 12 How would you declare an array of thre function pointers where ‘ech function receives tvo int and returns afloan? Q 73 ‘Would the following program give a compilation error or warning? main) foul the fllowing program compile? i) ina=10,4); void"; jake 8a; ie ke pit (we ak): 715 fould te following code compile successfully? int) pet" 71"Sundaran"}); Answers Ai char p=malee (100); A 72 hari ser ‘sur= (char far*) 8000000; A 73 [No, *ptr+-+ increments the pointer and not the value pointed by it, ‘whereas ++4ptr increments the value being pointed toby pr. A 74 Cries A 7 "COC Esse) A 76 1022 Az 004 2 2 79 (asia *((int*) +4); 710 tot of places, some of which are: Accessing aay or string elements Dynamic memory allocation all by reference Implementing linked lists, trees, graphs and many other data structures rt 712 (or) in it) 71s > Here no typecasting is required while assigning the value to and om k because conversions are applied automatically when other ite types are assigned to and from void *. 16. ‘Test Your C Stills, A 714 No. Aneror would be reported in the statement ++ since arithmetic ‘on void pointers is not permitted unless the void pointer is ap- propriatly typecasted A 716 Yes. It would print m of Sundaram. Chapter 8 More About Pointers a1 $the NULL pointer same as an uninitialised pointer? 82 nwhich header file is the NULL macro defined, as is it that fr lage memory models NULL has been defined as ‘and for small memory modes a just 0? 84 a's the difference between a nll pointer, a NULL macro, the "IINUL charsctor anda null string? 8 ‘est Your C Skills Q 86 ‘What would be the outpat ofthe following program? Inthe programming yl adopedin 8.6 good? Q 88 ‘What would be the output ofthe following program? ‘nce ‘sto main) ( Print ("Se sizeot (NULL), sizea |"); Q a9 How many bytes are occupied by near, far and huge pointers? Chapter 8: More About Pointers 2 Q a0 Whatdoes the error"Null Pointer Assignment’ mean and whatcauses | thiserror? Q sn ‘How do we debug a Null Pinter Assignment error? Q sz ‘Can anything else generate a Null Pointer Assignment eror? Q sn ‘Are the thre declarations char **apple, char *orangel J, and char cherry If] same? Q su Can two different near pointers contain two different addresses but refer tothe same location in memory? Q a5 Can two different far pointers contain two different addresses but refer tothe same location in memory? 80 ‘Test Your C Skills Chapter 8: More About Pointers a1 Q a9 "What warning would be generated on compiling the following pro- Q a Can two different huge pointers contain two different addresses but ‘refer tothe same location in memory’ Q an ‘Would the following program give sny warning on compilation? ecluie'sdon" [How would you eliminate the warning generated on compiling the following program? = maint) Wouta te following program give any warning on compilation? Q 521 ‘tncudestgo ht mmain() i How would you obtain a far address from the segment and offset, fat pti =25505 addresses of a memory location? char ‘ps Q s22 How would you obwin segment and offset addresses from a far address of a memory location? 2 Test Your CSkills Q 328 Ina large data model (compact, large, huge) all pointers to data are ‘32 bits long, whereas ina small data model (iny, small, media) all, pointers are 16 bits long. Q 824 ‘A near pointer uses the contents of CS register (if the pointer is pointing to code) or contents of DS register (ithe pointers pointing {o data) for the segrnent part, whereas the offset partis stored in the 16-bit near pointer Q 525 ‘What would be the curpu of the following program? main) charter ‘a= cx00000120 char far“ = oxo0r00020, charfar‘c= 000120000; it(ansb) rin (He (azze] rin") it(b=re) ein ( elo"); i(abasarcatd>c) rin ("nbye"); Chapter 8: More About Pointers. 83 Q a2 fl char huge ‘a= 0400000120; char huge "b= 0x00100020; char huge ’e= 0x00120000; it(asbaka>ckab>c) Brit ("nye") A 32 Infiles "stdioh” and “stddet.h" A 33 ‘Because in small memory models the pointer is two bytes long ‘whereas i large memory models itis + bytes long. o Test Your C Skills A 84 For each pointer type (like say a char pointer) C defines a special pointer value which is guarenteed not to point to any object or function of that type. Usually, the null pointer constant used for representing a null poiner is the integer 0 A ss A nul pointer i a pointer which doesnt point anywhere, NULL macros se to eres the mall pier in sous ‘thas a value 0 associated with it. co ‘The ASCII NUL character has all its bits as O but doesn’t have any relationship with the nul! pointer. ‘The mull string is just another name for an empty string“ A 86 5 A 37 No, Oy income of pins shuld NULL and 0 be cans equal, NULL snd ot be ued when ober Lind aoe ‘Sere Een fought werk satalaycol pepsin ANS pena detlon ef e NULL maces [Te e705 “ich nares hatte NULL vl a Wo on poo ‘Chapier 8: More About Pointers 8S A ss 21 A 89 “A near pointer is 2 bytes long whereas afar and a huge pointer are 4 bytes long. A 810 ‘The Null Pointer Assignment erro is generated only in small and ‘medium memory models, This exror occurs in programs which at- ‘tempt to change the bottom of the data segment. ‘In Borland’s C or C+ compilers, Borland places four zero bytes at the bottom of the data segment followed by the Borland copyright notice "Borland C+ - Copyright 1991 Borland Int. In the small, and medium memory models, a nll pointer points to DS:0000. Thus ing a value to the memory referenced by this pointer will ‘overwrite the first zero byte inthe data segment, At program termina- tion, the four zeros and the copyright banner are checked, If either has been modified, then the Null Pointer Assignment error is generated. Note that the pointer may not wuly be null, ut may bea Wild pointer that references these key areas in the data segment. A su In the Integrated Development Environment set two watches on the Key memory locations mentioned in 8,10, These watches, and what, they should display inthe watch window, are *(char"j44es Botand C++ + Copyright 1991 Borland I" 86 Test Your C Skills (char‘j0 0.000000 ‘Ofcourse, the copyright banner will vary depending on your version ofthe Borland C/C++ compile, Step through your program using FX or FT and monitor these values inthe waich window. A the pint where one of them changes, you fave ust exeeted a Sateen tat ses a pointer hat as pot been rope ‘The most common cause of this error is probably declaring a pointer and then using i¢ before allocating memory for it. For example, comple the following program in the small memory model and execite it include “os fe ‘ince “t0." inctde “sting in) { char ‘py, “banner baer = (char *)MK_FP (_08, 4); pri | banner: banner): _tepy ("The word up saga’); rit pt = Spe (void fa) 0); Print (anne: is, banner); ) ‘One of the best debugging techniques for catching Null pointcr assignment errors is fo tur on all warning compiler messages, Ifthe above program is compiled with warnings tumed off, no warning ‘messages will be generated. However, if all warnings are turned on, both the strep) and pring calls using the ptr variable will geneiate .wamings. You shouldbe particularly suspicious ofany warnings that «8 variable might be used before being initialized, or ofa suspicious pointer assignment. (Chapter 8: More About Pointers 87 [Note that a Noll Pointer Assignment error is not generated in all, ‘models. Inthe compact, large and huge memory models far pointers fre used fr data, Therefore, null pointer will reference 0000:0000, lorthe base of system memory, andusing it will not cause corruption "ofthe key values atthe base ofthe data segment. Modifying the base of systemmemocy usually cases systemerash, however. Although it would be possible that a wild pointer would overwrite the key ‘values it would notindicateanll pointer. Inthe tiny memory mode, DS = CS =S. Therefore, using a all pointer will overwrite the beginning of the code segment. A sp “Yes, using a wild pointer that happens to reference the base area ofF the data segment may cause the same error since this would change the zeros of the copyright banner. Since data corruption or stack corruption could cause an otherwise-vald pointer tobe corrupted and, pint tothe base ofthe dats segment, any memory corruption could result inhi error being generated, Ifthe pointer used in the program ‘statement which corrupsthe key valves appears tohave been proper- ly initialized, place a watch on that pointer. Step through your ‘program again and watch forts value (address) to change. A 813 No A au No 58 Test Your C Stills A 815 ‘Yes A 516 No A a No A 38 ‘Yes, Suspicious pointer conversion in funetion mai A 319 Non-portable pointer assignment in function main. A 820 Use the typecast sr = ( char far * ) 0x88000000 ; A 821 rlude ds rman) har ‘seg = (cha) 8000; ‘har of = (char) 08000; Qhapier 8: More About Pointers 89 chartar’p; aN FP (209,011); char fr) oxBeD00000 seg: ( char") FP_SEG (ser); of | char*) FP_OFF (ser); 8.23 24 825 Bye 4b and refer to same location in memory sil the ist three fail because while comparing the far pointers wsing =— (and !=) full 32-it value i used and since the 42-bit values ane dierent the i ful. The lastifhowever gets satisfied, because while compar- NE using > (and >=, <, <= } only the offset value is used. for parsion. And the offst values of , band c are suc that he last liom i sate. 0. Test Your C Skills A 326 Hello Hi Hello Hi Unlike far pointers. huge pointer are ‘normalized’ 10 avoid the strange behaviour asin 8.25 above, A normalized pointer is a 32-bit pointer which has as much ofits value in the segment address as possible. Since a segment can siart every 16 bytes this means that the offset will only have a valve from Oo F. Huge pointers arealways kept normalized. As a result for any given memory address there is ‘only one possible huge address - segmentoffst pair for it Chapter 9 ie Arrays 91 at wuld be the output of the following program? sn) prin ("ated ec, sizeof (a), steal (BJ) ‘pint ("ted sizeof (a), sizeof ("B)) 92 the following statements would arr[3] and ptr{3] fetch te same haracter? * a an) = “Suprise = "Supreed 98 Fhe statements in 9.2 does the compile fetch the character ar7/3) i pr in the sare manner? 2 Test Your C Skill Q 4 ‘What would be the output of the following program, if the aray begins at adress 12007 rain) ( inant] ={2,3,4,1,6); rit (0° ary, soo (ar); d Q 95 Does mentioning the array name gives the base address in all the contexis? Q 96 ‘What would be the output of the following program, ifthe aray bins at address 654867 ral) int ant} = (12,14, 15,23, 45) ; print ("6u 9", ar, Bar}; ) Q 97 ‘Are the expressions arr and arr same for an aray of 10 integers? ‘Chapter 9: Arrays 93, Q v8 ‘What would be the output of the following program, if tre aay begins at 654862 rman) ( int an} = (12,14, 15,23, 45); nt "hu r+ 1, Barr+ 1); 1 Q 29 When are char af J and char *a weated as same by the compiler? Q 9.10 ‘Would the following program compile successfully? ‘ma charal)="Suratok prin ("nts "a, p); } Q on What would be the output ofthe following program? man() 4. Test Your CSkills { fat af}= (124,23, 45,67): 5 Pam esi} ao); Q 02 \ [A pointer to a block of memory is effectively same as an array, Q 918 ‘What would be the outputof the following program fthearray begins ats472? main) { into 4.2.9.4, 4321, 7.890 i 1 PAM ort kart Q ou ‘What does the following declaration mean sett}; Chapter 9: Arrays 95 Q 0 If we pass the name of a 1-D int array toa funetion it decays into a ‘pointer to an it. IF we pass the name of a2-D array of integers to © function what would ic decay into? ; Q 916 How would you define the function fin the following program? int anfMAXROWIMAKCOL]; fun(ar); Q on ‘What would be the output ofthe following program? rman) { int aa] =( inet pir Aa) funy 8pt7) ) fui) print nts) 6 Test Your C Skits Chapter 9: Arrays 7 Answers When array name is wed with sce operator ‘When the aay name san operand the & cperator Ast A 96 12 mt 65486 65486 A 92 A 97 Yes ‘No. Eventhough bth nay ive the same adresses asin they mean to eiferem tings, ar ves the adress of the fis in wheseas nee ‘Barr gives the addres of aay of rs, Since these acess happen No. For arr[3] the compiler generates code to start at loeation ar, ‘move three past it, and fetch the character there, When it sees the expression pirf.3 it generates the code to start at location stored in pir, add thre tothe pointer. and finally fetch the character pointed Inother words, arr[3}is three placespastthestartof the abject named ‘rr, whereas pir|i] is three places past the object pointed toby por A 94 1200 10 A 95 No, Whenever mentioning the array name gives its base adress tis ‘Sti that the array has decayed int «pointer, This decaying doesn't lake place in two situations: to be same the resus ofthe expressions are same. A 98 65438 65196 A 99 ‘When using them as formal parameters while defining a Function. A 3.10 No, because we may assign & new sting 0 @ pointer but not 10 an anny. A su Test Your C Skills A 912 True A 915 65880 65496 A 914 Drei a pointer io an aray of 10 imegers A 915 decays into a pointer to an array and not a pointer toa pointer. A 916 fan (int af IMAXCOL} i ) fu (int ("ptr [MAXCOL) ptr pointer oan array") ¢ ) A 9.17 Chapter 10 Strings Q m1 ‘What would be the ourpu of the following program? sain) pri (5+ Facil") Enor Faseimile mle [None of the above & vee 102 ‘What would be the ouipat of the following program? rmain() ( charst chars] it(si a2) it inEqul) Chapter 10: Swings 101 10 Test Your C Sis Print (“Unequal”); D. None of the above A. Emel Q ws Sc eal dee How would you ouput Won te seen? Th Rabat ors Q@ v6 Q ws ‘What would be the output of the following program? rmain() Are ator: A. Brror Bd Crd D. abodefgh Q 104 ‘What would be the output ofthe following program? main) ( char stf7]= "Stings" print ("%s', str); ) A. Bror B. Strings ©. Cannot predict ‘What would be the output ofthe following program? a charch =X; rn ("64 c,sizoo | ch), sizaot ‘8: ) 1 1 e A pnee Q 07 ‘What would be the output ofthe following program? rmain() rin (ed 400, Siac (3, sizeof (3), size0f(3)): pose 02. ‘Test Your C Skills Q ws Is the following program correct? rmain() char ‘st = "United char‘st2="Font; rn is, a) , Q ws How would you improve the cade in 10.8 above? Q w10 [nthe following code which function would get called, the wer Aetined strep or the one inthe standard library? maint) ( ‘har tri] ="Keep nda Beautiful. emigrate!” char st, stepy (si, st): rit sss): } _sepy char, chars) t while('s) { Chapter 10: Swings 103 Q wn Can you compact the code in spy) into one line? Q 112 ‘What would be the output ofthe following program? ran) ‘ chars] =| ‘Frogs, Do’ Not, "i, Tey, "Coak"}; iat Ed aoa (et), szot (st) ) Q ws "How would you find the length of each string inthe program 10.12 above? Q wu ‘Whats the difference in the following declarations? 104 Test Your C Skills Q 01 ‘While handling a string do we always have to process it characte by character or there exists a method to process the entire sring as one Answers A ior ci A 102 B A 103 c A 14 C. Here sr! J has been declared as a7 character aay and int it a8 character string has been stored. Ths would result into oversrting ofthe byte beyond the seventh byte reserved forthe ary with "0 ‘There is always a possibility that something important gets overwrit. ‘en which would he unsafe, A ws print n") Chapter 10: Strings 105 A 16 8 A w7 B A 1s No, since what i present in memory beyond “United” isnot known and wes ataching “Front tthe end of ‘United’ thereby overt: ‘ng something, which is an unsafe thing to do, A 109 rmain() ( chars) ="; ) A 10.10 User-defined srepaf) A 1011 tepy (char char's) { 106. Test Your C Skills hile ("+=") ) Chapier 11 A wr Structures, Unions and oe Enumerations A 1013 ‘main() hast} = Fs ie’, ey, “Cont ous ‘nls Whats th similarity beweenastructure union andanerume for (i= 0; ic 5; itt) ‘ Pein (Se sf stent); i As ite ould the following detaaton work? Here a is an array big enough to hold the message and the "0" following the message. Individual characters within the array can be intas changed but the address ofthe array would remain same. Mat; On the other hand, p is a pointer, initialized to point to a string constant. The ponler p may be modified t9 point to another string, Q ous butif youattemptto modify the string t which ispointing the result, is undefined (Can a stricture contain a pointer to itsel? Q ius jn oy the exror, if any, in the following code. A 10.15 A string can be processed only ona character by character basis 108 Test Your CSkills ‘ypedet smut { intdata NODEPTR inks )NODEPTR:; Q us How will you eliminate the problem in 11.4 above? Q us Point out the error, if any, in the following code. ‘void modty (suet emp); stuctem { har nanef20); ray’, 95) madly (82); Print ("ins “6, ename, eye}; ) Fae apasoe ‘sup (ponane |: poages poage +2; (Chapter 11: Structures, Unions and Enamerations 109 w7 “Would the following code work? itn; char namelt); D: a char newnamel}="Rahul ; sul amp ‘p= (stuct emp *} malo (sea (struct emp )-1+ tion (nowram) +1); polen= tien {nennamne| siropy ( poname,newname ); prt et ot poe): Q us (Can you suggest a better way to write the program in 11.7 above? Q us How would you free the mesnory allocated in 11.8 above? 10 Test Your Cis Chapter IH: Simetures, Unions and Emumeraions 11 sna anpe2= Q 10 ae (Can you rewrite the program in 11.8 such that while feeing the ‘memory only ane call free) would suffice? Qo un ‘What would be the output ofthe following program? ral ‘atel emp "Davi 28); print (ase ota); ) Q ur Point eu the error, if any, inthe following code. main) ( strut omp pi | “The stuctures ave equa") ) Q us How wouldyou check whether the contents oftwo structure variables are same or not? Q uu How are structure passing and retumning implemented by the com= piter? Q us How can redritesracies rom data les? Q us6 Ifthe following structures written toa file using fwrite),ean fread) read it back successfully? struct emp t charm; int age; fur ( Be, szeo(e), 110); ue Test Your C Skills Q un ‘Would he following program always output the size ofthe strectore as T bytes? sinc ox thar ch ii: long ina: i Q 18 ‘What error does the following program give ad what is the solution fori? man) t siruc omp { char name); float sal; i" su emp off); shee; l44) scarl (8%, f.name, 8] sal): } Q uv How can I determine the byte offset ofa feld within a structure? Chapter 11: Structures, Unions and Enumerations 3 Q@ 120 ‘The way mentioning the array name or function name without [] oF () yield their base addresses, what do you obtain on mentioning the ssructurename? Q un ‘What is main) returning inthe Following program, struct ransacton i intsn0: char dsc); char oo foal amount; 1 Heres he main program. ne cam) ‘stat rensacon scant ("éd is ke WF, ts, Ldesc, td, BLamount) rit eds Sr no, tes, Lt, Lamount) Q u2 What would be the output ofthe following program? ‘man() t ort { 4 Test Your CSkils (Chapter 1: Structures, Unions and Enumerations 1s peaenay, 5 Geo Q naz ip Din (‘size = ud sizeot struct a}; ‘Since enumerations have integral type and enumeration constants are ) of type int can we fcey intrmix therm with other intcgral pes, ‘without eros? 1129 e Q 128 ‘What's the difference between a stricture and a union? Q usa Is it necessary that sizeof al elements ina union shouldbe same? Q 125 Point out the error, if any, in the following code, Is there an easy way to print enumeration values symbolically? Q 120 ‘What isthe use of bit fields in a structure declaration? Q 130 (Can we have an array of bit fields? rmain() C union a nswers ( inti Aint char chia}: All of them let you define new data types. A m2 Yes ‘Whats the difference between an enumeration andasetof preproces- soritdefines? 6 est Your C Skits Chapter 11: Structures, Unions and Enumerations uz A us eto, intdeta; struct node tak; (Certainly. Such structures are known as self-referential structares. A ius ‘A tpedef defies a new name fora type, and in simpler cases ike the one shown below you can define a new structure type and a ‘ypedef for tat the same time. Iypede ct fl char name intege emp: However, inthe structure defined in Q 11.4 there is an eror because a typedef declaration cannot be used until tis defined. In the given, ‘code fragment the sypedef declaration isnot yet defined tthe point here the ink fel is declared. A us ‘To ix this code, frst give the structure a name (‘struct node"). Then dectate the fink field as a simple struct nade * as shown below: "ype ct pede c int; stl nade nk; J NODEPTR:; ‘Another way to eliminate the problem isto disentangle the nppedef declaration from: the structure definition as shown below i | ypede scl node ‘NODEPTR; Yet another way to eliminate the problem isto precede the structure declaration with the ‘ypedef, in which case you could use the NODEPTR typedef when declaring the lnk field as shown below: ‘ypede struct poe (NODEPTR struct ado ( int deta NODEPTR next a In this case, you declare a new typedef name involving struct node even though seruct node has not been completely defined yet; this you're allowed to do. I's a matter of style which of the above Solutions would you prefer A 6 ‘The siuctempis mentioned in the prototype ofthe function modifi) before defining the siructure, To solve the problem just pl the prototype after the declaration ofthe structure or just ad the state ‘ment siruct emp before the prototype A uz ‘Yes. The program allocates space for the structure withthe size adjusted s0 that the name field can hold the requested name (not just, us ‘Test Your C Skills fone character, as the structure declaration would suggest). {don't know whether itis legal or portable. However, the code did work on all the compilers that I have tied it wth A us “he tuly safe way to implement the program is to use « character pointer instead ofan array as shown below’ ‘rode calor h> si emp inten char name h main(} t cha newnare =" ‘stetomp ‘p= (stust onp*) alle (sel ete emp): olen = sen (nenname ) ‘>name = maloc (polen+ 1); i Obviously, the "convenience" of having the length and the string stored in the same block of memory has now been lost, and freeing Insianee ofthis stueture will equi two calls the function fee), A us ‘tee (p>neme) feetp) (Chaprer 11: Structures, Unions and Enumerations 119 A 1.10 ‘ilo caloc> shuctero i lens char*name; a main) t char bud = malls (zee stu p+ on (romano + 1); set enp p= (ststemp bal: Fen = in (nena) froname= bi + size (suc emp); Sty (p>name ewan) prin (eds pen pram | , min A uu DRAVID When a strucute is assigned, passed or returned, the copying is done ‘monolithically. This means thatthe copies of any pointer elds will, Point o the same place asthe original, In other words, anything Pointed o isnot copied. Hence, on changing the name through €2.7 ‘tautomatically changed e/.n A ue Structures can’t be compared using the bull in ==and !=operations This ie because there is no single, good way for a compiler to 120 ‘Test Your C Skills implement structure comparison. A simple byte-by-byte comparison ‘could ail while comparing the bits present in unused padding in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison might require unacceptable mounts of repetitive code fo lrge structures. Also, any compiler- ‘generated comparison could nat be expected to compare pointer fields appropriately in all cases; for example, i's often appropriate to compare char * Fields with temp rather than with A in ‘anc ame ‘har 2] iniage strut emp ot = {"Dravi’, 28) struct emp e2 scat ("Xs Sd, 2 B2.age i (sotomp(, ) paint "The stucues ae equa); eke print ("Te tutus ae urequat , structomp(stuct emp x, stuct emp y) i ) it( stomp (xn, yn): (age = yage) teu |0) retum 1) ) (Chapter [1: Structures, Unions and Enunerations 2 In hort if you need to compare two structures, you'll have fo write {your ov function 10 do so which cartis out the comparison eld by Tiel A ss ‘When structures are passed as arguments to functions, the entire Structure is typically pushed on the stack. To avoid this overhead many programmers often prefer to pass pointers to structures instead ‘of actual structures. Structures are often returned from functions in a location pointed toby anextrs,complier-supplied ‘hidden’ argument tothe function A 1115 To write out a structure we.can use frit) as shown below: wit (Se, szeot(e), 1.19) ‘where ¢ sa structure variable. A comesponding jread{) invocation ‘an read the structure back from a file On calling forite(it writes out sizef{ e bytes from the address de. Data ils written as memory images with write), however, will not ‘be poriable, particularly if they coniain floating-point fields or pointer. Thisis because memory layaut of stuctues is machine and compiler dependent, Different compilers may use different amounts ‘of padding, and the sizes and byte orders of fundamental types vary across machines. Therefore, structures written as memory images ‘cannot necessarily be read back in by programs running on other ‘machines (or even compiled by other compilers), and this is an important concern if the data files you're writing will ever be inter changed between machines. 7 ‘Test Your CSkills A 116 No, since the structre contains a char pointer while writing the ssrctue othe disk using write) only the value stored in the pointer rr would get writen (and not the sting pointed by it). When this, stricture is read back the address would be read back but itis quite unlikely thatthe desired string would be presen at this address in emery. Aim No. A compiler may leave holes in structures by padding the frst ‘char inthe stracture with another byte just to ensure thatthe integer that follows is stored at an even location. Also there might be to extra bytes aftr the integer to ensue thatthe long integer is stored ‘tan address which isa multiple of 4. This is done because many ‘machines acess values in memory most efficiently when the values are appropriately aligned. Some machines cannot perform unaligned accesses at all and require that all data be appropriately aligned. ‘Your compiler may provide an extension to give you contot over the packing of sirututes (ie, whether they are padded), perhaps with a pragma, but tere is no standard metho. If you're wortied about wasted space, you can minimize the effects ‘of padding by ordering the members ofa structure from largest 9 smallest. You can sometimes get more control over size and align- ment by using bitfield, although they have their own drawbacks, A 118 Error:Floating point formats not liked. What causes tis eror to ‘occur? When the compiler encounters a reference to the address of a ‘loa, it ses flag ave the ink Tink inthe floating pointemulator. Chapter 11: Structures, Unions and Enumerations 123 A floating point emulator is used to manipulate floating point num- bers in runtime library functions like scan!) and atof). Thre are some cases in which te reference tothe floais a bit obscure and the ‘compiler does not detect the need forthe emulator. ‘These situations usually occur during the initial stages of program, evelopment. Normally, once the program is fully developed, the emulator willbe used insuchafashionthat the compiler ean accurate Iy determine when to link inthe emulator. ‘To force linking of the Noating point emulator into an application, {just include the following function in your progran ot LinkFoat (void) i oat a= 0, b= 8a, "cause anultortobe Inked) ‘'b; suppress waring-varnot wed"! ) “There is no need to cal this funtion from your program. A 1119 ‘You can use the offet macro given below. How to use this macro has also been shown in the program, Actineotsetye, mem) (it) char" (ype *)0)- mem «(cher ('vwe")0)) pe seta char name); Int age; float sa ig ‘Test Your C Skill ) Int ofeatofname,ofetolago, fsttsal; ot stu name) nt (" ofseolname floetclage = oft (struct 99) rn (MS, stlege); fiscal = ose (struct sa): prin (sc, sos): } ‘The output of this program would be o1s7 A 120 ‘The entire structure itself and notits base adress. A 121 ‘A missing semicolon atthe end ofthe structure declaration is causing ‘main() to be declared as returning a structure. The connection is Aificult o see because ofthe intervening comment A uz sire =2 Chapter 11: Siructures, Unions and Enuerations 1s ‘Since we have use bit lds in the structure and the total number of bits is turning out to be more than 8 (9 bts to be precise) the size of the structure is being reported as 2 bytes. pA aay, ‘A union is essentially a structure in which all ofthe fields overlay ach other; you can use only one field at a time. You can also write to one field and read from another, to inspect atype’s bit pattems or ‘nterpre them differently. A 12 No, Union elements can be of diferent sizes. Ifso, sizeof the union issize ofthe longest clement inthe union. As against this ho size of a structure isthe sum ofthe size of its members. In both cases, the size may be increased by padding A 1125 ‘The ANSI Standard allows an initializer forthe first member of union. There is no standard way of initializing any other member, hence the error in initializing 22, Many proposals have been advanced to allow more flexible union initialization, but none has been adopted yet. IF you still want (0 inialise different members ofthe union then you can define several ‘variant copies of a union, withthe memipers in different orders, so that you can declare and initialize the one having the appropriate frst ‘member as shown below. union a ( 126. est Your C Skills tion 221 = (512): unin 22 = (0,2): ‘ A 126 ‘Theres hardly any difference between the two, except tha define has a global effect (throughout he fle) whereas an enumeration can have an effect local to the block if desited. Some advantages of ‘eoumerations ae thatthe numeric values are automatically assigned whereas in efi we have toexplicitly define them. A disadvantage is that we have no control over the sizes of enumeration variables. A 27 Yes A 1128 No. You can write a small function (one per enumeration) to map an ‘enumeration constant toa string, either by using a switch statement or by searching an aray. Chapter 11: Structures, Unions and Enwmerations 17 A 1129 Bitfelds are used to save space in strctures having several binary flags or other smal fields. Not thatthe colon notation for specifying the sizeof a fcid in bits is valid only in siractures (and in unions); ou canna we this mechanism to speci te size of arbirary A 1130 No Chapter 12 Input/Output Q 2 Wha ould be the ouput the following rogram? main( ) { iaan7; print (ote, a): } Q 22 ‘What would be the output ofthe following program? print (wei6at a): print (5. ind (i821 prin (eso. a) 130 Test Your C Skills (Chapter 12: Inpua/Ouaput 131 Q ws Q ws Pint out the ecror, if any, inthe following program, Inthe flloning cose ste tat» fcc dot man) ‘al eee unin char pn"): Bem ) fo =topen( Wat"): Jo points 19 ee ‘A, The first character inthe file IR (Saati ape B. _Asrutur hich contains char points which points tote oa feschneerincie 1s CThename of he file D. None ofthe above ) Q ws Q 26 ‘Ifa fle contains the lin “Lam a boy\vin” then on reading this line Point out the ero, if any, inthe following program, i ‘nto the aray sr using fgets) what Would str contain? since “sat? tel ® uignd char; © “Lamaboyino” FLE"p: D. “lamaboy” f=lopen( ‘ial, ); 27 whl ((ch= ge (fp) x EOF) q ret (4 eh) Point out the error if any in the following program, 0801p) Finds “adote 13 12 Test Your CStils Chapter 12: npa/Oup = Q 210 rues ¥ ‘Point out the error in the following program. {p= fopen (“rial “t") ‘fseek (fp, 20, SEEK_SET) “include “sto.” ‘dose (fp): ‘a : FILE “ps Qn Sears} fp = fopen ( ‘tial *r"); ‘To print out a and b given below, which printf) statement would ‘while (Heat (2) i gets (str, 80, fp); float 14; puis (sit); foaled; 1 felose | fp); AL printf ("Sef %E", a,b); ’ Bint ("arava © pint ('aLtaLre ab): Dp igs D. prin (“er Q ws bd: Point out the errr in the following program, Ancute“stdoht ‘Toscan a and b given below which scanf{) statement Would you use? ay Neat: charch; yes, what would be the utp? ‘man() { intn=5; it one.) Chapter 12: Inpu/Oupus 135 Q 25 ‘What isthe * in the pring) of 12-14 indicative of? Q ws Can we specify variable fleld width in a scanff) format string? Q 20 ‘To tackle a double in pring) we can use %f, whereas in scan) we should use 9 Q wis (Out of fet) and geist) which function is safe to use? Q 1219 A file writen in text mode can be read back in binary mode, Q 12.20 ‘We should not read after a write to fle without an intervening call to flush), fuek() oF rewind). 136 Test Your C Skills Answers A 11 BOF has been defined as Adefine FOF -1 in the file “sto. end an unsigned char ranges from 0 to 255 hence when EOF is rea from the file itannot be accommodated in ch. Solution isto declare ch as A 25 Noeror. A 26 ic (Chapter 12: Input/Output 137 A 27 Instead of 20 use 20L since fseek() needs a long offset value. A ws A. Itis possible to print a double using Ef A no D A 220 “The last ine from the file "ial" would be read twice. To avoid this, hil (op (st 80, fp) = NULL) puts (8); A iu You would ot got a chance to soply a character forthe second ‘scang{ statement. Solution is to precede the second scanff) with the following statement ‘sh stn) would lush outthe eter hit forthe previous scanf])tobe lashed ‘ut from the input stream, ie. keyboard. 3 ess Yur Cis, Chae 12: put bs A ve (A nu %% facts), because unlike fgets(), gets() cannot be told the size of the ‘Sterinoumichtestigsopidwole sere: Asari es Ivavagea poi ofoverowobutl ‘The path of the filename should have been written as "e:\tc\\rial”. A 20 A au Fae A 220 Ys ee Tne A 2s t indicates that an int value from the argument list wil be used for ‘eld width. In the argument lst the width precedes the value to be printed, In this case the format specifier becomes %5d. A 1216 No. A'*"inscanf format string aftera% signisused forsuppression ‘of assignment, That is, the current input field is scanned bat not stored, A 217 Tue Chapter 13 Command Line Arguments Q 181 ‘What cote the‘ and vin argc and arg tnd fo? Q 132. ‘According to ANSI specifications which s the correct way of declar- ng main() when it receives command line arguments? ‘A. main (int arge, char “argv ]) BL main argo, argy) int arge char *argvt] C.main() cea ETT: D. None ofthe above Q aa ‘What would be the output ofthe fllowing program? P sampla ‘man {int age, char "arg 2. Test Your C Skills ( arge = age -(arge- 1) int (8, glare 1): Q 4. If different command line arguments are supplied at different times ‘would the ouptut ofthe following program change? past ter car) print (4, aga] Q 15. {tthe following program (myprog is rn from the command in as, peg 123 shat would be the output? an ap, ‘a }) ins for(i=0;icange;h+) ins ro); Q ws. the following program (myprog) is run from the command line as Chapter 13: Command Line Arguments 143 smypog 128 what would be the output? nin (it age, tar‘) Pat |=) + argv + arg; i ("5 {fhe following program (myprog) is run from the command line as mypreg 1 23 hat would be the output? ‘mah (int age, char ‘a }) 144 ‘Test Your € Skill ee Q 23. ‘Would the following program give the same output at all times? main(int are, chat aro) { sep {rg helo): ‘ep are], good morning"): eda ac Q 180. Ifthe following program (myprog) is run from the command line as, Iyprog one two tree what would be the output? Pa eae oe Q 210. fhe following program (myprog) is ran from the command ine as nyprog one two tree what would be the output? Chapter 13: Command Line Arguments 145 main int arg, char ro) rin (Sc, 44a) ’ Q on “The variables arge and argo are always local to main . Q we “The maximum combined length of the command line arguments ‘including the spaces berween adjacent argusments is A. 128characters B, 256characters C6 characters 1D, _Iemay vary from one operating system to another Q sn. What wil the following program output? rman (it arg, char ‘rg char ‘er { ini, for (ints args) it (“6 * om) List ofall environment variables List ofall command line arguments Enor NULL, poep 146 est Your C Skills program (myprog) is un fom the command line as what would be the ousput? fa bt hee) int; for(int; L ea 13.15. {fhe following rogram (msprog) sun fom the command ine x yprg *e what would be the ouput? sin(etenc cero) inti tor( ares) rin (36s a) Chapter 13: Command Line Arguments 7 A B fF all. files inthe current directory c D. None ofthe above Q 110. ‘If we want that any wildcard characters in the commandline argu- ‘mens should be appropriately expanded, are we required to make Any special provision? If yes, which? Q sir Does there exist any way to make the command line arguments available to other functions withoutpassing them as arguments tothe Function? Q w8 [Ifthe following progeam (myprog) is run from the command line as rmyprog Jan Feb Mar ‘what would be the output? ‘inchte "dosh min) font) 48 Test Your C Skills it ("6 *_erov) ) Q 1319. If the following program (myprog) is present in the directory ‘eNbe\ues then what would be is output? ‘main(int age, char ‘aa ) eee A. MYPROG B. C\BCITUCSIMYPROG ©. Enor BD. cspeaucs Q 1320 Which sancasy vay to exraetmyprs tom he opto program 13.19 above? a Q 1321 Whieh ofthe following is true about argv? Itis an aray of characte pointers Iti pointer tan array of character pointers itis an array of strings A B ie D. None ofthe above Chapter 13: Command Line Arguments 149 Q wx Ifthe following program (myprog) i rn from the command line as myprog menday tuesday wednesday thursday what would be the output? ree he (~arge > 0) print ("Hs "Hrqr) 5 ‘A. myprog monday twesday wednesday thursday B. monday tuesday weinesday thursiay CC. myprog tuesday thursday D. None ofthe above Q 13.23. Ifthe following program (myprog) i un from the command line as prog tay testy sunday what would be the output? tal at ge, char arg }) 1 pe, a: Am Bf, CC myprog. 150 Tet Your CS eet eee ee 151 D. fiay Cn By Q 1924 Q 1226 Ifthe following program (myprog) is un fom the command line as rryprg tiday twesday sunday ‘what would be the outpat? main(int rg, char arg) i pe ela Am a ip © myprog, D. friday Q 1325. Ifthe following program (myprog) is run from the command line as, imypreg fda tuesday sunday ‘hat would be the output? main int rg, char ‘erg }) eaters a Bf If the following program (myprog) isn from the command line as myprog fiday ueseay sunday ‘what would be the output? main(int teary char ‘agv}) hie szeotarge) print (48 xg -seooary |: ‘A. myprog friday tuesday suiiday B. — myprog friday tuesday C. sunday tuesday friday myprog D. sunday tuesday friday wers: A 131 (Count oF arguments and vector (aray) of arguments 2 Tes Your Ctl (haste 12: Command Lins Arguments 153 CASAMPLEEXE ee! A 14 z % A nn A ns F CAMYPROGEXE 123 ae A 136 , « A ia A is7 . Wen ata) eso conse arg 8 mmr icant dso (argv[0} being a file name) and hence returns a zero. A ts A na “ A ne No A 139 3 A 13.0 ‘Yes. Compile the program as fee myprog wadargech This compiles the fle myprog.e and links it with the wildcard expansion module WILDARGS.OBJ, then run the resulting ex- ‘cutable file MYPROG.EXE Isa est Your C Skills If you want the wildcard expansion to be default so that you won't have to link your program explicitly with WILDARGS.OBJ, you can ‘modify your standard C?-LIB library files tohave WILDAROS.OBI linked automatically. Toachieve this we have to remove SETARGV from te library and add WILDARGS. The following commands will invoke the Turbo Librarian to modify al the standard library files {assuming the curent directory contains the standard C libraries and WILDARGS.OB)) {ib cs -setargy witiargs ti ce -sotargy wiargs ‘i cm -otargy aiargs tb cl selargy widens ib oh star swidargs A 1317 ‘Yes, Using the predefined variables _arge, arg A 13.18 ‘CAMYPROG.EXE Jan Fob Mar A 1319 B A 1320 Fncude “dh main (int re, char ar }) char dive, df60], namo) ex]; prin ins): tnspit (rg) ev, ame, ext); Chapter 13: Command Line Arguments 155 } A A A ee ee ee > Print ("tests dive, de, name, ext); 13.21 13.22 13.23 1324 13.25 13.26 Chapter 14 Bitwise Operators Q us ‘What would be the output ofthe following program? man) { inti=92,j=000, km; A. 323232320 B 00000 032323232 D, 3232323232 Q u2 ‘What would he the output ofthe following program? at unsigned int m 158 ‘est Your C Skils Chapter 14: Binwise Operators 159 rin, -m); Hl tz?) A fe print ("ox x x Mx xx 0b 6, 4,61); 5. 0060 , car D. ara Q us ‘What would be the oupat ofthe following programm? main) 1 None ofthe above Q us Point out the error in the following program, mat) unsigned int Dao=d ace?; Domed ena; Q us To which numbering system can the binary number 41011011111000101 be easly converted to? Q us “Which bitwise operator is suitable fr checking whether a particular bicis on or off? Q uz ‘Which bitwise operator is suitable for turing off a particular bit ina number? Q us ‘Which bitwise operator is suitable for puting on a particular bitin a number? Q us (On left shitting, the bits from the lef are rotated and brought tothe right and accommodated where there is empty space on the right? ‘ Wo Tet Your € Sil Chapter 1: Bie Opertr 161 Q u0 omer fatlsoue Tih) Letsitings amber salvay eqaaeatomuesn ibe aera Hosea) rd yes") Q un ‘Left shifting an unsigned int or char by 1 i always equivalent to ‘mulplying itbe 2. Q urn ‘What would be the output ofthe following program? main) ( unsigned char = 0380; int (tice 1); ' A 0 B 256 C100 D._Noneof the shove Q us ‘Whats the following program doing? main() i Uunsgned int = {x01 02, 0308, x08, x10, 0320, x40, 90); unsigned char; Putting off ll bits which are on in the number ‘Testing whether the individual bits of» are on or off ‘This program would give an error None of the above pomp Q uu ‘What does the following program do? main) ( chat*s; fn (128.2); rit ie ¢) ) {un | unsigned intra nt base) sialic char buf]; char rs pir = Abu [sizeo (but )- 1]: ‘1284567B6abeda num % base) rum = base: 162 Test Your CSille Chapter 14: Bitwise Operators 163 ) whe (rum <0) 1 slg itu; roku ine=0: ) scan (4, num), for(;rums mur >= 1) ‘A. Iteonverisa number to given base B. Ic givesacompilationeror it(rum at) ©. None of the above eos ) Qian jae ‘line HARSZE 8 ‘A. _Iteounts the number of bis which ae on in the mumbe nm ‘Helne MASKS) | 1 < 4); I A om oof C om00 Domo Q us In the statement expression! >> expression? if expression! is a signed integer withislftmostbitsetto I then on right-shiftng itthe Hosier eee eee eee result of the Statement would vary from computer 10 computer. Q 120 ‘What does the following program do? maint) { unsigned intr ini; sean (“Su umn); fer[i=0;i< 16;i+4) prin ("Se (num cel 1 << 15 21:0); [eprint all even bits fom um Ieprints all oda bits from mum It prints binary equivalent of mum None of the above poee Answers A tt A A 142 cs Chapter 14: Bitwise Operators 165 A 143 A A us -since there is no operator like A us Hexadecimal, since each 4-digit binary represents one hexadecimal digit A us The & operator A uz ‘The & operator A us The | operator A 9 False 166 est Your C Skills Chapter 14: Bitwise Operators 167 A 1410 A 1417 No A A uu A us Yes ‘A.On computers which don’t suppor sign extension you may get B. A m2 A 1419 B Tre A wis A 1420 B c A mu A A mu char anfUMSLOTS{50); Tle, 20); if(TEST (an, 40)) A 116 ‘one CLEAR(x,y (XBITSLOTY)]&= MASK) Chapter 15 Subtleties of typedef Q wi ‘Are the properties of i,j and x, yin the following program same? ‘ypadal unsigned ang int ui): unsigned logit x,y Q 52 ‘What isthe type of compare inthe following code segment? Aypadel int (prt char char*) itun compare; Q ws What are the advantages of using pedefin a program? 170 est Your C Skills Q ws Is thete any differnce in the #define and the rpedefn the following code? If yes, what? ‘ypedet charting ‘dete sting dchar* sting tt 82; sting 689, sh Q 5 tppedefs have the advantage that obey scope rules that is, they can be declared local to a function ora Block whereas Adfines always havea glotal effect. Q 56 Point out the error inthe following declaration and suggest atleast three solutions fort. ‘ypodel strut ( Int: NODEPTR ink; J INODEPTR ; Q 7 Inthe following code can we declare anew typedef name emp even though struct employee has not been completely defined wile using syperdef? Chapter 1S: Subileties of ypede im ‘ypedet snc employe “pr ust employ ( char namel2) intage; ret; i Q 58 ‘There isan error in the following declarations. Can you rectify it? ‘yposet set ( inten BPTR int; yAPTR; typede trct { ned; APTR inka; }-oPTa; Q 9 [ha othe folowing declrtons mean? fypodel char ‘pe; Iypede cfc) Iypede ‘pe: ‘pede pip ttt): ‘npedel be ‘Pippo: Bie aN: i. Test Your CSkills Q 1510 How would you define a[N] in 15.9 above without using typedef? Q wu Improve the following code using typedet. sthetrade Int data; fat data; sir node “let; ‘teu nade “ight i struct nse pr pir = struct ned *) malo (sizeot struct node}; Q 1522 Is the following declaration soveptable? ‘ypedet ong no, “pttano; pitonop; Q ws Inthe following code what constant, por the character itis pointing te? ‘ypodel char“ chap; const char pi Chapter 15: Subileies of ypedet 173 Q wu Inthe following code isp? an integer or an integer pointer? ‘ypedet intr: pt. pes nswers A 1 Yes A 52 Iisa pointer to function which receives two character pointers and recurs an integer. A 153 ‘There are three main reasons for using pede (2) _Temakes writing of complicated declarations lot easier. This helps in eliminating a Tot of clutter inthe program, (b)__ Ithelpsinachieving portability in programs. Thais, it we use ‘npedefs for data types that are machine-dependent, only the ‘npedefs need change when the program is meved fo a new ‘machine platform, (€) _Ithelpsin providing a better doumentation for a program. For ‘example, s node ofa doubly liked lists beter understood as pirolist rather than just a pointer to a complicated stracture 18 ‘est Your C Skills A 154 Inthese decaratons, «1,52, and s3 ae all reatedas char *,buts4is treated asa char, which is probably nt the inetention A 155 Te A 156 A nypedef declaration cannot be used until it is defined, and in our ‘example itis not yet defined at the point where the link field is Aeclared. ‘We cam fix this problem in three ways (@) Give the structure a name, say node and then declare the link Field asa simple struct nade * a8 showin below: ‘ypede stustnode int data; struct nde ink; }"NODEPTR: (©) _Keeptherypedef declaration separate from the structure éefini- tion struct ede Chapter 15: Subteties of typede 175 \ypode suet node * NODEPTR (©) Precede the structure declaration with ypedef so that you can use the NODEPTR typedef when declaring the link fel ‘ypodetstuct node *NODEPTA; struct nada ( inedata: [NODEPTR ink ) A 157 Yes A is “The problem with the cade isthe compiler doesn't now about BPTR. ‘when itis used in the first structure declaration. We are violating the rule that a rypede declaration cannot be used uni itis defined, and ‘nour example it isnot yet defined athe point where the link! field is declared, ‘To avoid this problem we can define the structures as shown below: stusta c inte; stret nt a siuctb int ata struct inka; 116 Test Your C Skills Chapter 15: Subteties of typedef Ea h A 19 ‘patel sucta"APTA: Pe is poimtrto cha. ‘pel tut °OPTR: foe is funtion reurning pointer to char wipe ispointertoa function euring poitertochar ‘The compiler can accept the Fld decaraton srt par within fotpe isa fonetion rewming pointer to function sirut ay even though it hes not yet heard of struct b (which is rctucrng pointer to char “incomplete” at tht pint). Occasionally, itis necessary to precede Pope isa poimer to function returning pointer 0 this couplet withthe fne fantion turing pointer to char Pipe al isan aay of N pointes to function returning std; pointers to funetions returning pointers t0 harates ‘This empty declaration masks the pairof srvctae declarations iin a iner stops) from a diferent struct b in an outer seope. After declaring the two stuctues we ean thea declae the typedef PA, 20 separately as shown above char" aNDAIK) Alematvey, we can alo define the rypedefs before the structure ‘Chapter 16: The const Phenomenon 183 main) const har un); peaneeet: const char “un() © amv ) Q we Point ou the error in the following program, pat const char un) wae) ) const char "un() t , Q@ wis ‘What do you mean by constcorrectness? Q wu ‘What would be the output ofthe following program? return Helo! rman) ( 184 Test Your C Skills [Charter 16: THe toner Phenomenon im ‘const intx=5 ; { ini consti =7; pies; ie consig= ak; pbx 10; Pind (4 "q): gp mae ) Abr Q wir B10 enor ‘Whats the differncein the following delartions? Di Garbage valve cone car's; Q 6.15 ‘char const’s What would be the output of the following program? Q wis n= ‘Whats the diference in the following declarations? cons imix=5; ora char* cont; ee cher const* const; Q 15.19 Is the following a propery writen function? Ifnot, why not? ‘Aas Bs 10 int fn (cone inin) © Error D. Garbage value ae azn'n; Q we return a: Point out the error in the following program. main) 18s, Test Your €Suils Chapter 16: The const Phenomenon wm Answers A 167 A 161 [Nowhere other than through initialization can a program assign a valu 0 a cons identifier. x should have been initialised where its declared. A 162 A A 163 A A 164 “The dimension ofan array must always bea postive non-zero integer constant which maxis not A 165 yourbuf the program is trying (0 ptr pointer is constant, In pt ‘modify it, hence an error. A 166 ‘per can be modified but not the object that i is pointing to. Hence ‘iris a constant pointer ta constant object. We can neither modify ‘pir bor the object itis pointing to. A ws We can modify the pointrs source as well as target. However, the ‘object to which source is pointing cannot be modified. A 169 ‘The function change) receives 3 char pointer and an it and returns pointer toa constant char. A 15.10 Waring: Suspicious pointer conversion. This occurs because caller fun )retuns a pointer ta const character which is being assigned 0 ‘pointer toa non-const, A wu No A 16.12 fin retuns a pointer to const character which cannot be modified, A 16.13 + 188 ‘Test Your C Skills ‘Aprogramis ‘const correct’ ifitnever changes (a more commonterm is mutates) a constant object. A 16.14 B A 115 ic A 1.16 ‘Waring: Suspicious pointer conversion. kan be pointed ro only by pointer toa cons; q isa const pointer. A 1617 ‘There is no difference. A 16.18 ‘There is no difference. A 16.19 Since fn() would be called by value there is no need to dectare as ‘a conitsince passing by Value already prevents an() from modifying Chapter 17 Memory Allocation Q m4 ‘What would be the output ofthe fallowing program? mman() { cha: ha fun) stint) rin (58) ) chat un() char bute) sttpy (buf, "RAM - Rarely Adequate Memory"); retu (bullet); ) Q 2 ‘Whats the solution for the problem in program 17.1 above? Bs Tes Yu il hag 17: Menor Alain is tase s00.4 Q 1s pat Doe it any ahr lin rhe 17.17 sup Q 4 How would you dynamically allocate a -D array of integers? Q us How would you dynamically allocate a 2-D array of integers? Q v8 How would you dynamically allocate a 2-D array of integers such that we are able t access any element using 2 subseripts, as in arf Q How would you dynamically allocate a 2-D array of integers such that we are able to access any clement using 2 subseripts, asin arrfil[jP Also the rows ofthe aay should be stored in adjacent ‘memory locations Q ws How many bytes would be allocated by the following code? ‘nchde “alc ht ‘etino MAXROWS P 1 PCH MARCON mae WHARON st) Q 179 What would be the output ofthe Fllowing program? elude “aoc ‘cine MAYROW 9 ‘cine WANCOL 4 ri) Ine(-pIMAXCOL; inl") MAXCL) mate (MAKROW* tot ("p | Print ("ad a, steal (p), soc"); ' Q 110 Inthe following code psa pointerto an array of MAXCOL elements, Also, malloc allocates memory for MAXROW such arrays. Would these arrays be stored in adjacent locations? How would you access the elements ofthese arrays using p? ‘deine MAXROWS foie MAXCOL 4 main) i inthis int("p)aaxcouy 12 Test Your C Skills, = (lnt(* JMAXCOL]) mateo MAXROW *sizeot(‘p)) Q wu How many bytes would be allocated by the following code? lug ‘alloc ‘Heine MAXROWS #tefne MAXCOL 4 ne in ‘p)MAXCOLIMAKROW; = (It [*) INAXROWIMAXCOL]} male (zee ("p)); Q re ow ould you dynamically allocate «3-D aay of integers? Q m8 How many bytes of memory would the fllowing code reserve? ‘cue ‘alloc? main() ( ity: =(in*) mateo (288"256); (p==NULL) Print (“Alocton fal) Chapter 17: Memory Allocation 193 Q 4 How would you freethe memory allocatedby the following program? cute aloe ‘eine MAXROW 3 ‘eine MAXCOL4 main) ( in“pi; ) mao ( MAKROW* sot in"); i.e MAXROW; i) Bills (in) mateo (MAKCOL* zee int)); a‘) Q 15 How would youfteethememory allocated by te following programm? rude “act fete MAXROW 3 fine MAXCOLA mran() { ep bjs ={{nt) malloc MAXROW size int"); Pj0]=( nt) mals (MAXROW " MAXCOL” sot int) for(i=0;i. yes, how? Suppose we ask realloc) to increase the allocated space for a 2osinteger array toa 40-integer array. Would it increase the acray space atthe same locaton at which the aray is present or would it try to find a different place forthe bigger array? Q i725 We allocating memory any thr pole poit nt th same ples of memry we hve teats ete eer pes oF Q 1732 Pereciestiac eens Point ou the exror, if any, inthe following code. ee ea Chapter 17: Memary Allocation 199 A 173 ‘ude ‘leet ‘main() t car's; char tani) sti): print (“es", s )5 froe(s); 1 ‘char * fun() t The outptis unpredictable since bufer is an ato aray and wood ts di when the convo goes back to mal). Thus s would be pointing fir=(char*) alec ( 20); ; toanaray which no longer exists ky PAM arly Adequate Marry’) retun( 1); A 172 ) a A ira her's include “alloc h* ‘char * fun); ‘define MAX 10 main() stunt): t pi (688) B 1 * } malloc ( MAX * sizeo! (int) ) Te MAX i} chart) ( 21; ‘stat char bufter(30) ; ‘print ( “Wn, pl) Sty (bul "PAM Rarely Adequate Nemo); ) umes: r 2a rep ¥abs stad Chapter 17: Memory Allocation 20) A 175 fede aoc atin NAXROW 3 ‘ine WAXCOL 4 a pA 77 males MAXROW* MAXCOL sian) frei MOM fea for(j=0;}-s); 4 A iis Way teo(00); In shor when we alloatestrstes cotnng poimets 0 other ‘ree(p) | dynamically allocated objects before freeing the structure we have to fife eich pointer inthe src A me A 1720 ‘No. ine pris an unntised point usb pointing sme Unknown loan in emery-Te sing that we pen would ot 1m most implementations of lc) the munber of byes allocated Store atthe locaton to nich prs pointing tery Ovewng irstored adjacent tothe allocated back Hence spl forfee) ee eae, toknow how many bytes to dealocte, Amn A 121 me 5 chars) = "Ope Guree= Pin, A nz ‘treat ($1, $2) + print (“Yes", $1); ) No A ie A iz bia Yes hing the eat fantom as shown below Fi“ A in po ‘The memory chunk at which sponing as no been ro Jot ay; frecing te memry punted toby te st point pin en pe Cet") natc(20); =P: int") elle (0,40); it(ts=NULL) Ideally we should have used: 206 ‘Test Your C Skis Print| ‘Cannot ealloat, leaves provous alocstd reson unchangec”) + the aay expanded athe sae region ee free (p);* delat th oral aay" /satpto nniy allocated regen") ) A 174 Both. Ifthe frst strategy fails then it adopts the second, IFthe firsts suocesful it returns the same pointer that you passed to it otherwise diferent pointer for the newly allocated space. A 1725 If realloct) expands allocated memory atthe same place then there isn need of readjustment of other pointers. However, ifitallocates new region somewhere else the programmer has to readjust the other pointer. A 1726 ‘As against malloc), calloc() needs two arguments, the number of elements to he allocated and the sizeof each element. For example, (nt) ello (1, sioo (int); Chapter 17: Memory Allocation 207 ‘would allocate space for a 10-integer array. Additionally, calloc() ‘Would also set each ofthis element wit a valve 0 ‘Thus the above call to calloc() is equivalent to: nt*) maloe (10° seo! Int) }; ‘memset (p0, 10° size n1)) A 1737 ‘The same that we use with mallc(), ie. feet), A 17.28 The A 1729 KB A 1730 Use the standard library functions farmalloc() and fafree(). These functions are specific © DOS, A 131 ‘Yes. Using interrupt 0367, the details of which are beyond the Seope ofthis book 208 Test Your C Skills A 3 Chapter 18 ie aging ts ee by malt) we so Variable Number of Arguments Q ws ‘Which header file should you include i you ae to develop a function which can accept variable numberof arguments? vararg.h siclibh sidio.n sdargh Q we ‘What would be the curpu ofthe following program? poEe incude ction nude starg b> rman) fun (char 9, .) rl {un | Nothing spect, 4.7.11,0); tt valsiptr; 210 Test Your C Skills lint um; vast (pl meg): um= vag (lit) um= vag (iit) pint ("oe ram); ' Q ws Isitmecessary than function which accepts variable argument ist, there should at Teast be one fixed argument? Q 4 ‘Cam the fixed arguments passed to the function wich accepts vari- able argument ist oovur at the end? Q ws Poin out the ero, if any, inthe following program, include main) ( vatun(3,7,-11,0}5 ) van (int, .) { va stp int um ‘um = va_org (pt int) (Chapter 18: Variable Number of Arguments print (ed, ram) Q 186 Point out he erro, if any, in the folowing program, ‘nude dango. rman) 1 varun (3,75, 112,066): 1 vat (ina, .) fat"; Intum; va stat (pn); um = va_arg (py, ; print (enum Q wr Point out the errr, iPany, inthe following program, Frcude sary» rman) i fun (4,7, 11,0); ) fun(..) t 20 212 ‘Test Your C Skis vasiptr; iennum va stat (int): um = va_ag (int) print (6, sum): ) Q ws ‘The macro va_staris used to iitalsea pointer othe beginning of the ist of fixed arguments. Q 19 ‘The macro va_arg is used to extract an argument from the variable argument list and advance the pointer to the next argument. Q 110 Point ou the error, if ny, in the following program, Vinci steargh* ‘main() { Cisplay (4. ) play otra.) i hare: int) va lstpr fer 18: Variable Number of Arguments 213 va_sta pr, num) forli=1 ( enum; j++) vary pr char); prin (60's); ) ) Q wi Mention any variable argument list funciton that you have used and ts provoiype. Q wp Point ou the error, ifany, in te following program. ‘ncude stag ‘main() delay (4,125,185, 145,443); y(t. fat ints va lotpr; va sat (pt rum). tort ( jssnum; t+) = va.arg (pr float) pri ("arat”01: 214 Test Your C Skills Chapier 18: Variable Number of Arguments 215 ' Q 15 Can we wits faction that takes variable argument ist and passes aos Be In oes ncn (vic ks « Vr PR sents) Point out he erin the following program, foe "aeoh Qher mrain() ( Point out the error, if any. in the following program, spay (Hole 4.2125, 195,145,440) t sue seen mmain() lea (hart un, nun.) ( { pay (Ho 4 12, 19,14 44); float; int}; ’ va lett display (tas) -va_stert (ptr, $) 5 t ‘¢=va_erg (ptr, double ); ‘show (s, ..) print (*in86t*,¢); 1 , stow (char) t Q wis en ima Can we pass a variable argument list to a function at runtime? va. sat.) Veo a-va.e (Bt): print ("S6 a)| Q 1815 } Wie sig vate mpeeat tates We ap he hee ellipsis...) How would you rewrite program 18.17 such that showy) is able 10 handle variable argument list? eee aS ‘Chapter 18: Variable Number of Arguments 217 Q wis piston; r= tue: use the following pring to print a fong int why Tam not warned ‘idea opens bout the type mismatch? ee sno) incon Q 18.20 vast pir va_start( ptr, 8); cor eng a PSSTA AL satire, Cen: Q 1821 (bz = va_arg (py int(*)()); tral ‘How can a called function determine the number of arguments that y echt Pr t Q 1522 stint (Hele): 1 Ree SU ae eas a a Scalers cee tere Q 1323 Point out the error in the following program, Q 3.24 tae *sidargh* ‘How would you rectify the error in the program 18.23 above? int ("PTs int (‘p2\(), inuni(), una); 18 ‘Test Your C Skills Answers. A 11 D A 182 4 A 13 Yes A 184 No A 185 ‘Since pir has not been sef at the beginning of the variable argument list using va_startit may be pointing anywhere and hence a call 0 vi_arg would fetch a wrong inter. A 126 Irrespective ofthe type of argument passed to a funetion receiving variable argument lit pirrmust be of the type va_list. (Chapter 18; Variable Number of Arguments 219 A 187 ‘There is no fixed argument in the definition off) A ws False A iso Tre A 1810 ‘While extracting a char argumentusing va_arg we should have used (0 var (print. A isu it (cost char oma.) A 2 \While extracting float argument using va_arg we should have used = va_arg (pr. double). A 1813 While setting the ptr tothe beginning of variable argument list we show have used va star (po, num2 ) 2 cle 220 ‘est Your C Skills A 181 No. Every actual argument list mustbe completely known atcompile tim In that sensei isnot tucly a variable argument lis. A815 Yes A 18.16 Yes A 117 ‘The call to sho) is improper. Ths is not the way fo pass variable argument list toa funetion, A 18.18 include ‘dag ‘main() clsplay ("Holo 4 12,19, 14, 44); ) lplay (chars) va.istpr: va_stat (pt); a Chapter 18: Variable Number of Arguments 221 show (chart vast tt) for(i=Ozicajis) ‘n=va_arg (pir int) print "inn 1 } A 18:19 When a function accepts a variable number of arguments, its prototype cannot provide any information about the number of arg ments and type of those variable argumenis. Hence the compiler ‘cannot wam about the mismatches. The prorgammer must make Sure that arguments match or must manually insert explicit typecast, A 1820 ude sto h> cea tery > mman\) fe oid pit (char): char* carver (unsigned in int; inti 5 chart] ="Ivanete ae hare ota." ) void pint chant.) ( sharp: (Chapter 18: Variable Number of Arguments 223 222 Test Your C Skills case's ai; = ¥a_a1g (0p char") unsgnedu; puts (8); cha: break: vaste: = a_arg| rp, usigned rt; va sat | agp ft); us (convert (u, 10)), break; us va_arg arg, unsigned int) puts (comer (u 16); roe) Break putas (*P) putas) continue; break; ) ) pe ) aac) va.end (arp); case’ ; ar pit) har sone unsianed int nmr bes putchat i): ( break: static char bu; =~ shar pr i vary (rp int) na set (ut)-1 ce uf | set bu) 1] { ted , meme) puts {conven 10)) Break: case's vent uaa arp, ursigneint) prea us (coment (u, 8); beh; 224 Test Your C kis (Chapter 18: Variable Number of Argurents 25 pe=hind; A 1821 play ("ye 52); ) Trcannot. Any function that takes variable number of arguments asthe abe to determine from the arguments herseves howe many play (chars. of them there ae. The print) function, for example, dos thi by { looking for format specifiers (Sed et) in the format sting This is expt) P2105 thereason why such fonctions fal badly ifthe format string does nt vaLkept: smath the argument is. typed i (“urep() vast (pis) : pt =a.arg( net). A ex (apn) p= aang (Yet) When the arguments passed are all f same type we can think of (Heys pasinga sentinel valo like -1 or or aNULL pointe atthe end of ) the variable argument list Another way could be to expicily pass the count of numberof variable argument ni ens pr ilo"); és ) va_arg cannot exteact the function pointer fom the variable argu fina) tment Ist inthe manne tied here i prt (WH); A 18.24 p Use npedefas shown below: fine ‘sara ht ‘main() { Inept): Ine (p2): intuni(), una); Chapter 19 Complicated Declarations Q wi (What do the Following declarations signify? ime ine "PAV char argv: void (10) ) int int); char far er char far re 10] ine a3} int far *P): char far *ser1,*Sc72 ine ftablel 1) void) = ( fad, fou, fa, fi} 5 int (ep )801 + int p30] void Femp(): void ("emp 0: har FOTO har (* (x13) 151; void (*F (int, void (730) ine (fine, nt ** (#) (int, int) void (*£¢ void (* Cin *, void *"), int (* ¢void *, int *) 3 char far * fat "ptr; char far * near *pt hae ft “huge *pe Cae ROROZEr RS ZOTmOOE> 28 ‘Test Your C Skills Q w2 ‘What would be the output of he following program? rman\) ( char near" nea‘; char near far “2 char near* hugs “3; Prin (dso (pit), sizeof (2), sant (td): Q ws ‘What would be the output of the following program? main) c charter“ near"p charter "far "2 charfer* huge ‘ed; int ("dd snot prt), sieot (pt), zoe tra}; Q 94 ‘What would be the output ofthe following program? rman) char huge * huge‘ ie ("sd Sd sz (pr) szeot |p), tet }): Chapler 19: Complicated Declarations ) Q ws What would be the output of the following program? ‘oir; 23 “pt; izet (ptr), sect pt), seo (pra }); huge rin (54S Q 6 ‘What would be the output of the following programm? charfar “huge “near ‘pra rin (“Yd 4, ier), seo “2, sie (“pra }): Q 7 What would be the ouput ofthe following program? rman) ( char huge *near® far ‘prt char near “fr “huge i 230 ‘Test Your C Skills charfar *huge* near ‘pia int (Sed eet (pr) szact (“2 size (rd); Q we ‘What would be the output of the following program? mman() 1 char huge * near far “le chat near far *huge 2 chatfar “huge “nea ‘pt pit (ede, Sizeot 7p), ter) siz 3) } Q 29 ‘Ae the following 1we declarations same? char tar farses char far arse Q 1910 ow would you declare the following: An aay of tee point char Anaya te hor pers Ato an aay of ice cas 2 pine toa fncion wish ecelves ann pon and returns ‘otter toa faction which recevies nothing and rerurs tag Chapter 19: Complicated Declarations 231 Q wi CCan you write @ program which would implement the following declaration. id (* int, 0d (*)) 5 Answer A 19.14. fis a function returning pointer fo an i A 19.18. fsa pointer to function which returns an int A 1916. argo is a pointer toa char pointer A 1910. isan array of 10 function pointers, where each function reeivestwo ‘ns and returns noting, A 1918. cris far pointer a char. (far pointer sa pointer which contains an address which lies outside the data segment), 232 Test Your C Skills A w91F. ‘arr an array of 10 far character pointers, A 1916 ‘ais an array of 5 function pointers. Each ofthese functions receive far pointer to an ine and returns an in A 1918. serT is far pointerto a char, whereas scr? is anear pointer to a char. A 11 fable ian ary of & fn pint ich pot the ution Fo) fou Jet. Eachf these fanstion accept othing andretun ‘nine A 19.14. piris a pointer to an aray of 30 integers. A 191k. piris an aray of 30 pointers to integers A 1911. ‘mp is a function returning pointer to vid. Chapter 19: Complicated Declarations A 191M. ‘mp isa pointer to Function which returns a vid A 191N. 4. inetn ening pointe oars of pine enon A 1910. Xsan aray of 3 pointers to functions returning pointer to oF hans ne A 19.1, ray fi8 8 pointer toa function which returns nothing and receives as is parameter an integer and a pointer to a function which receives ‘othing and returns nothin. A 1919 fis @ pointer to funetion which retuns a pointer to an ine pointer and receives two arguments a pointer foan inrpointer anda fnction pointer which points toa function which receives two pointers fat pointers and retums a pointer to an ine pointer. A 191R, {isa pointer to function which rewms nothing and receives two arguments, both function pointes: the frst function pointer points to 234 ‘Test Your C Skills «function which returns nothing but receives two arguments ~ an int pointer and & pointer toa void pointer; the second function pointer points tea function which returns an infpointerand receives a pointer toa void pointer and an int pointer. A 1915. iris «far pointer toa far pointer to char, or in easier words, ptr Contins a far address ofa far pointer to a char. A i917. char, or imeasier words, pir ‘prs anear pointer to afar pointer a char, 01 Contains a near address of afar pointer to a char. A wiv. iris a huge pointe oa far pointer ta char, orn easier words, pir contains a huge address of a far pointer toa char. A 192 244 A 193 244 A 194 244 Chapler 19: Complicated Declarations A 195 442 A 196 444 A 197 222 A 1986 444 A is9 No A 1910 char“; char ete: char‘; Moat {pi }(nt*) void P () A 1911 main) i 235 voi ("i void (790) seat) Chapter 20 void (“P)(): t Library Functions B (*9123,0) 1 voi un (int oid (79)()) print (Helo ' Q 21 voi fun) t What do the functions ato), ioa() and gevt{) do? Show how would ‘you use them in a program, Q 22 Does there exist any other function which ean be used to convert an integer ora float a string? IF yes, show how you would use it Q »3 How would you us gio into sc ay of ssi Q 24 How would you use gsor() function to sort the names stored in an auray of pointers to strings? ) 238 Q 205 How would you use bsearch) funetion fo search a name storedin an ray of pointers to strings? Q 206 How would you us the Funetons sin(), pow() grt)? Q 27 How would you use the function memepy()? Q 8 How would you use the function memset()? Q 9 How would you use the function memmove()? Q 210 How would youuse the functions feek, fread) firite()and fill)? Q 21 How would you obtain the current time and difference between two times? Chapter 20: Library Functions 239 Q w2 How vould yous the fen rndomie) nd random Q 13 ‘Would the following program always output ‘Banglore"? ‘mah() t chara] = "Bangor 440010"; char sa); simopy (st, si. 8) pri ("s,s ) Q 21 ‘Can you shorten this code? rain) i charetr] charst210) Banglore - 40010" s2io)="0 stincal (sts, 8 | print ("48 82} 200 ‘Tess Your CSkills Q 215 How would you implement a subs) function that extracts a substr- ing from a given sting? Q 2016 Given a sentence containing words separated by spaces how would you construct an array of pointers to strings conttining addresses of cach word in the sentence? Q 217 ‘Write the comparison function gs_compare(} forthe following code struct cate t intdm,y ly ‘sompare (const void" cont void"); main) ( struct dala = ( (17.11,82), (243, 78), (17, 11,62), {16, 12,76), (19, 2.84) kw : els) Chapter 20: Library Funetions 24) zoo {ste data) ‘sor (4,5, gs-compare) for(i=0;h<$3 ts) ri red dc, i. dm, ely) Q 218 How should we sort linked fist? Q 2019 ‘What's the diffemce between the functions rand), random), srand) and randomize)? Q 22 What's the difference between the function menmove() and memcpy? Q 221 How would you printa sting on the printer? Q 2022 ‘Can you use the function forint to display the output onthe sereen? 22. est Your C Skills Answers A 201 stoi) Converts a string to an integer. ‘toa() Converts an integer ta string, evi) Converts a floating-point number toa string elude “tb be man() char f= "12345"; cher utle5), sting) ints eatei(s) print "nt. got (2.141672, 4, bur rit it’, itor); oa (15, sting, 21; Print (ins sng): ) A 202 The function spring Jean be wsed for his purpose. This function also has the ability to format the numbers as they are converted tosteings ‘The following program shows how to use this function, fino sto ‘main() Chaprer 20: Library Functions oat b = 3.14 char sta}; sprint (st, puts (str) } A 23 include "sting ht incudetdb t siruct stud t intl; int mars; ‘har nam) F int sor. (stet std" stuct stu") int or name (stl std" stuct std”). int or mari (stuct stud, stut stud") mman|) ( stati stuct td ss 96, “Akshay" 2,87, "Mach 8, 85,"Aay" 10,60, "Sushmta ) innxw leer) w= e200! stuct stud) print (rn order of rol numbers: * ‘oot (5,4, sortm) Test Your C Skills for(x=0; x24 34+) rit (iid sa, se rolno, sia} namo, s]mars ) prt (rn rer of nares"); fon (ss, 4,1, so name); for(x=0:x<4 x44) rit Bid sc, se ono, sy} name, x] mars ) pet (inn order of mas") sor (5,4, sor mais for(x=0;64 444) rit (Wed sc kro, ssxname,ssixmatks) ) int sot. (stuct std‘, sbust stud 2) Gi , retum (tt >rano-t2>rln ison name (stuct tut, stuct sud 72) C retum (stomp [name name} ) int soars (structs, stuct std "2 i ) A 204 clude tng include “i rom (2>marks-t->arts): it sot_name (const vid, cone ved") Chapter 20: Library Functions 245 rain) ‘ char“nanes|]=( Akshay Machu “wheat Sushi, Suen i inti; sot nae, §,szel (char), ot name) fer(i=0;1<5; 4+) print (“ns namest) ) intson_name (cont vid", canst voit] i 1 and 2 ae nays gonersto objects berg compared) char 2: cast apropitly* t= (char™) tees char retum (stem (*t1,122)) , A 25 fincas “sting include “tb int sor name corel void, const oid“) intbs_carpar char" char") ‘man() 246 ‘est Your Skills char‘rames{]=( ‘port (names 6, seo (char), er name): dre) for(i=0;1<5;i+) ps |"we4s', nest) wide = sizet|nanes() rel = sizeof (names wie esac 8, nares, nl wide, bs_compare) ite ain "Not found") ose iets"); int sont name | const vidi, const ci 2) tt anc are anaye pointer to objects bing compared“ hac 1,22 20: Library Functions ret (step ("t,122))5 ) abs cumpare (chars, char"s2) { raun (step ('st,"2)) ) A 206 ‘ncbte matin rman) t intang: flat agra, x,y 2: print inEntr he angen degrees"): sant ("Bang angred = ang" 14/160; xesin( angad); print neosine of argo Seis = "eng. y); A 27 clude ‘ment ech intavea char sr = Pray, at rEg lca, bat for stonger back” 8 Test Your C Skills Chapter 20: Library Functions char dest est = male area); memmove (des 1, 8a); male (area) int (is, dost) ; mom (del ee) pit “as e) ) pi (ie se) | et A Be felt‘ A m8 sms ticks mam { rae) ito; { chara] it aaa feat per chars] ="Bon jour Meda Jes a10a= sto (5); Fle ts: memes" 780-7); oan) pin ("i") { ' eng postin =O. iin: char A m9 featenp: ute em Finds fetigen| ‘stud ret tara ui ‘Unstle open i"): chat ea): Chea] « "Lie caer an yo eo rg ) ssotoap emg a Ps a1ea-stea(s2) i 250 Test Your C Skis (Chapter 20: Library Functions Print (into code no. to med"); ‘scar! ("rl it =citine (2,11); ile (eas (Be, saat (2), 1,6) rit “inProgram was active fr ul second', it); if(o10lno = ono) { pinata A 22 Scala nae, one) cued per=tonp Acie sab fsak (1 postin, SEEK SET) fw (66 szol(e). 8). man) break: t ) ‘eer: poston =fel (6): pin (“oP any et stop"): ) ile H)) ' fas ("You want oma oor) sour nom (590); hs gel) dy (arm 100); ie road); ‘ } 20.11 fee. A 213 fous “ett NNo, Because after copying the source string into the target sting imain() sirncpy() doesnt terminate the target string with a "OA better way ( cof copying would be: tine 111.2 double dt, 129] =10 imi=2; stmcat sts, 8) timo (811); Strmcai( always terminate the target string with a "0" sieep(i) time (82); 22 Tes Your Cty ptr 0: brary Func a { A 20.14 char st] = "This is atest; oar Yes sing pris stown ow on rn a 1 i (p= strtok (str, "*) arto rg Form) Sars i (0) = p sind sta. 81): wan ‘Print "Ses", st); t 1 p=strtok (NULL, ** foe) ro A 2015 ce nm i ‘char stri{] = ‘Banglore’ char st2{5}; i 1 xa chance trans 1 cherie a1); print (*So6", st); for |j=O:j sp2>y, 254 retum (1); eof («pt->m <«p2>n) rot (| se (spt-om>sp2>m) retum (1) lef (=pt->d d) retum (1); lef (spt nd> sp2>d) retum (1); ese retum (0) ) A 2018 ‘Often it’s easier fo keep the lis in order as we build it rather than sorting it Tater. Sul if we want wo sort the lis then we can allocate & temporary array of pointers, flit with pointers othe various nodes. in thelist, call qsort() and finaly rebuild thelist pointers based on the sorted aay A 2019 rand!) returns a random number, random) returns arandom number ina specified rang. srand{)intilises a random number generator with a given seed value, randomize iniualises a random number generator with a random value based on time A 2020 Both the functions copy a block of bytes from source to destination, However, if source and destination overlaps the behaviour of Chapler 20: Library Functions 255 Pia Dail ey ‘memepy() is undefined whereas memo orrectly. mem

You might also like