You are on page 1of 129
Contents Introduction 1 Declarations and Initslzations 2 Control Instructions 3 Expressions 4 Floating Point Issues 5 Functions 6 TheC Preprocessor 7 Pointers 8 More About Pointers 9 Amys 10 Strings 11 Structures, Unions and Emumeraions 12 TapowOurput 13 Command Line Arguments 14 Bitwise Operators 1S Sublets of npedef 16 ‘The const Phenomenon 17 Memory Allocation 18 Variable Number of Arguments 19 Complicated Declarations 20. Library Functions wi " n 37 47 35 31 107 129 141 157 169 179 139 227 237 Introduction “There is no dearth of good C programming books in the marke However, found that there is not much material which could help a C progratnmer to test his programming strengths, help improve his ‘confidence and inthe process hone his C skills. Hence this book: ‘This is not text book on C. Infact itis far from it. Iccontains a lot of questions sogregated topic-wise according to my perception ofthe language. Almost all the questions are real one's eked 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 in this 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 or using C-and you hhave questions about C that area’ tansweredin 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 on the C language. Also it doesn't cover every aspect of every operating systemunder which Cis nning, 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 0 the ‘questions in that chapter. You would find some answers more laborate than others. At first sight this may seem unnecessary. However, I have done this to give you the complete picture rather than oversimplifying or leaving out important detail have tried to avoid the questions whese answers are most obvious because te dea was not fo inrease the numberof questions, bt to presen questions which would force the readers to think vice before answering, Thatsin tune withthe spit of C- be precise, brevity has its own importance. So rll your sleeves and get on with the real questions. Good ck! Yashavant P. Kanetkar Nov., 1996 Chapter 1 Declarations and Initializations Qu What would be the output ofthe folowing progratn? 1 charfr 1,02 Print (Se a, aot (et), zoo (2)) } Q 2 What would be the output ofthe following program? invx=40 main) ints =20: rit (nex): Q we ‘What would be the output ofthe following program? ‘Test Your C Skills main() ( intx=40; vx =20: pri Wt" x); ) eek Qa Is the following statement a declaration ora definition? center int Qs ‘What would be the output ofthe following program? rman) { ext it i420; Print Se, sizet (1) 4 Would vary from compiler to compiler Error, undefined poe Isittructhata global variable may have several declarations, but only ‘one definition? Qu Is ittrve that a function may have several declarations, but only one definition? Q is Inthe following program where is the variable « getting defined and, where is it petting declared? af extmicta; int ("a ; ima=20; Q 19 ‘What would be the ourpu ofthe following program? man) ( tom eta; i ("ask ) fta=20; ‘Tost Your C Skills A 20 Bo © Gubage value D. Bror Q 10 ‘What's the difference between a defintion and declaration of a variable? Qu Ifthe definition of an external variable occurs inthe source fle before its use ins paneular function, then there is no need for an extern declaration inthe function, Qin Suppose a program is divided into three ils fl, f2 and 3, and a variable is defined in te file I but used inthe files 2 and. Tn such ‘case would we need the extemal declaration for the variables in the files 2 and f3? Q 12 When we mention the prototype ofa funtion are we defining the function or declaring i? Qiu ‘What’ te difference between the following declarations? 2, Chapter 1: Declarations and Intilisations xem int un); infu); Q us Why does the following program report ree fanction display!) man ( spay) } oid elspa) { nt ("ncatnanger’) Q 16 What would be the expat ofthe following program? ‘main() i etm int fun (fost) ita a=tun(at4) print (0a) intin aa) oat aa i ) retum (int) 2a); 6 Test Your C Skills Bas Enor Point out the error, if any, in the following program. stucteme charnamel20; int age: ’ some mare code may go here“ (Chapier I: Declarations and Initialisations 2 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? {(stutemp }; 7 any ober probolypes may go here! struct emp ( char namet2; intage: rit wks i, ee name, 8.298); ) Q 120 Global variables are available to all functions. Does there exist a ‘mechanism by way of which Tcan make it available to some and not toothes _ Test Your C Skills lisations Chapter 1: Declarations and Inti Q 2 ‘A. 00.000000 B. Garbage values What do you mean by at oe cee D, None of the above Q 12 |What would be the output ofthe following programm? Q 1x Some books suggest that the following definitions should be a preceded by the word static Is correct? ina)=(2.3); ital)=(2,9,4, 12,22); pe sd de ae) st amp o= “sandy 23) , A. Garbage values Q 125 B 233 elena 2 Peint out the error, ifany inthe following program, D. 000 : aR rai) Q 128 ( in (PK) =n i ‘What would be the ouput ofthe following program? pe fun) man) { { pr nLoudand es); sue np ) i char rae vee . Q 12 feats h Poin out the ror, if any inthe following program, sic onpe= (Toe): s Se iit (Wie age, eal) en : { io % Test Your C Stills Chapter 1: Declarations and Initialisaions uy union as in char ch 20 40. Incase ofa conflict beeen local variables, the one which is hi more local that gets the priory union a2= 512 print kd ec 2c 21). Pain , Q 17 ‘What do you mean by scope ofa variable? What are the 4 ifferent {ypes of scopes thata variable can have? Q iz What are the different types of linkages? Answers Au 42 aye: 20, Whenever there isa conflict between a local variable anda global, ‘variable itis the local variable which gets a priority Declaration A is D. extern in ‘isa declaration and nota definition, hence the eror. A 16 Yes A 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 tit, 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 ioplaces where te nature ofthe variableisstated butno storage isallocated. Ai Te A 112 Yes A 1 We are declaring it. When the function alongwith the statements belonging oi are mentioned we are defining the function A iu Thereis no difference except forthe fact that the first one gives a hint thatthe funtion fun() is probably in another source file. A 15 Here display()is called before itis defined. Insach cases the compiler assumes that the function digplay) is declared as Chapter 1: Declarations and Iniialisations 3 int depay|) ‘Thats, an undeclared function is assumed to return an inrand accept ‘an unspecified number of arguments. Then when we define the unction the compiler fndsthatitisretuming voidhence the compiler reports the discrepancy. A 116 1D, Theerroroceurs because we have mixed the ANSI prototype with K&R style of function definition ‘When we use ANSI protptype for afunetion and pass a flat tothe fanction it is promoted to a double, When the funeton accepts this double into afloat a type mismatch occurs hence the eror ‘The remedy for this error could be to define the function as: intun Hotaa) { } Aun Because of the missing semicolon atthe end ofthe structure desl tation (ihe intervening comment further abscures it) the compiler believes that ut) would return something ofthe the type struct emp, Whereas in actuality iis attempting to retum an in. This causes & Imismateh, hence an error results, a Test Your C Skils A 118 ‘The bes arrangement sto place each definition in a relevant. file ‘Then, put an extemal declaration in a header ile (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 of) A 120 'No, Theonly way this can beachievedis 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 teanalation unit isa set of source files seen by the compiler and translated asa unit: generally one file, plus all header files men- tioned in #include directives. A 122 . When an automatic array is partially initialised, the remaining aay element ae initialised to 0. Chapter 1: Declarations and Intialisations 15 A 123 ‘A. When an automatic structure is partially intalised, theremaining elements of the structure are initalsed 00 A 196 Pre-ANSI C compilers had such a requirement. Compilers whict conform to ANSTC standard do not have such a requirement A 125 Here we are iniialising the function pointer p to the address of the function fun) But during dis iniialiston the function has not been defined. Hence a eror. ‘Tocliminate this error add the prototype of the ju) before declara- tion ofp, as shown below: ter int fun); orsimply inti); A 126 Ina pre-ANSI compilera union variable cannot be initialised. How: lever, ANSI permits initialisation of first memeber ofthe union. 16 _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 rotype, A 128 There are hres diferent types of linkages: external, internal and ‘none. Extemal linkage means global, non-static variables and fune- tions, internal linkage means static variables and funetons widh fle Scope, and no Finkage means local variables, Chapter 2 Control Instructions Q 21 What would be the ouput ofthe following program? min() C inti= 4; switch (1) default: print (oA mouse i an elephant uly te Japanese") case print (nBreecing rabbis sa hare raising experience’) beak pit (aFecton isa dag") break oxo print pracite makes pect then nobed/ prot) Point out the error, if any in the for loop 1s i inti=t forts) i print (6c es) W(i>10) brook ‘A. The condition in te or loop is a mus. B. _Thetwo semicolons shouldbe dropped. C. The for lop shouldbe replaced by a while loop. D. Noeror. Q 2s Point ou the errr, if any, inthe while lop. i inti=1 while rine) itli> 19) ca ‘The condition in tho while loop is « mast, ‘There should be at least asomicolon in the while). The while Ioop should be replaced by a for loop. Noerror. poee Test Your C Skills rntrol Instructions 19 Chapter 2:6 Q Pint out the errr, if any, inthe while loop. rman() ( inti=1; while (<= 5 ( print (401) lia) 2 hore Point out the error, if any in the following programm man) { inti=4 j=2, soi (7) i case et "no oris human, to egies apn! company policy") Deak case) iit (you have ating ted, dont doithere*) break: Test Your C Q 2% Point out the error, if any, in the following program. main) int sth (i ( case! print (nRadoactv cals have 18 haves’) break case 1°2+4) nBotle fr renting wan”) Point out the error, if any, in the following program, rman) inta= 10. sca (a print (Programmers navel. They just ets nthe processing’: Chapter 2: Control Instructions 21 Q 28 Point out the exo, if ny, in the following program rain) ( inti= switch (i) prin (‘Halo’) common forboth cases “pint “ln uit") break case? print (Money is fhe root ofall woah) break } 1 Q 2 Rewrite the following st of statements using conditional operators bbla=1,0; H(a>10) b=2) Q 210 Point out the error, ifany, in the following program. ain) ( ima=10, Test Your C Skills 00:0 = 200 pi (aac) Q aun What would be the output ofthe following program “char sti] ="Parime musisars ae semiconductors; mans pont (a> 107 ‘A. Part-time musicians are semiconductors B. Part-time musicians ar semiconductors ©. Enor D. None of the above Q 22 Q 2 Q 2 ‘We wan! to test whethera vale lies in the range 210 40FSto7. 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 contol tothe beginning ofthe switl? Answers. Ao ‘A mouse isan elephant built hy the Fapanese Breeding rabbits isa hare raising experience A 22 D fa 23 A 24 goto cannot take contol toa diferent function A 25 Constant expression required in the: cond case, we cannot use Pa Test Your C Skills A 26 NNoerror. Constant expressions like | *2++4 are acceptable in cases of arviteh A 27 “Though never required, there can exist a switch which has no cases. A 28 “Though there isnnerror, respective ofthe value ofthe first prin) ‘can never get executed, In other words all statements ina sich have to belong to some case oF the other A 29 int a=, b, dara, ‘a> 107b=20: dumy= Note tha the following would not have worked a> 107D=20:5; A 20 ‘value required in function main(). The second assignment should be ‘writen in parentheses as follows: a5? 100 =(b=200) Chapter 2: Control Instructions. 25 A 2 A A 22 Asfarasefficiency isconcemed there would hardly be any difference ifatal. Ifthe cases ina switch are sparsely distributed the compiler may internally use the equivalent of an jfelre chain instcad of 3 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 ou Yes, though in way which would not be very practical ifthe ranges Ae bigger. The way is shown below: os Sich (2) ( case? case cased 7 some statements broek cases case 6 case 7 * some cer statements Chapter 3 break; ae Expressions No. continue can work only wih loops and net with switch Q 31 What would be the output of he following program: ran) i static int a0) ed eS, lal): What would be the output ofthe following program? print (5) ) 28 Q 33 “The expression onthe right and sie of && andl operators does not get evaluated if the left hand side determines the outcome. 2TrvelFalse> Q 04 What would he output ofthe following programm? i iti=2; pin (Sid 4,48): a4 43 44 ‘Output may vary from compiler to compiler Q 35 ‘What would be the output ofthe following program? pope maint) 1 imtx=10,y=20,25,1 pint (re) (Chapter 3: Expressions © Error D. None ofthe above, Q 26 ‘Are the following wo statements same? a<207b=30:0 (aee20)?b:c Q sr Can you suggest any other way of writing the following expression such that 30 used only once? a Q 38 How come thatthe C’standard says that the expression 0 is undefined, whereas, the expression [ates anne Is perfectly legal. Q 39 1f afi = i++ is undefined, then by the same reason i= {+I should also be undefined. But iti na so. Why? 30 Test Your C Skills Q 30 Wood he exesion p++ Q an Inthe following code in which order the functions would be called? be disallowed by the compiler, anf (25,14)°12( 1244) +100) fe Bint The order may vary from compiler to compiler None ofthe above pore Inthe following code in which onder the functions would be called? 11 (28,14)"12(124)) 4190); 1.2.0 Bat The onder may vary from compiler to compiler None ofthe above Q ss ‘What would be the output ofthe following program pomp ini=-3) C—O tt ‘Ghapir 3: Expressions p mati 8K 4] ok “atid ed Md ism) ‘What would be the ourpu oft © following program? nain() } Q ss Pasi pert fang pop in) a in: -3,j=2,k=0,m: Bee ojas vk Print (nse ed Ha Bm) , Q 16 What would be the ouput ofthe following program? man) { inti=-2,) m=ssi8a 2 ss Test Your C Skills Chapter 3: Expressions 33 ait (sd 5 Sd km) A } A 36 Answers. PA 37 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. But basicaly the behaviou® is undefined forth same reason asin 311 shove, A 33 ‘True, Forexample if ais non-zero then b will not be evaluated inthe expression all b A 34 . The order of evaluation of the arguments fo 2 function eal is, unspecified A 35 No A 37 "{(a mo nt ("1g (38.0); -4: Floating Point Issues Q 45 F Would the following prin) print the sae values for any vale of| -evesNo> it) foal; sean "28a; prt (ava); pant 3°) Y Q 46 ‘We want to round off x, afloat, to-an int value, The correct way to 0 s0 would be A y=(im) (x05); int( x +0575 (int) +05; (int) (int) x05 ) Qa Which eror are you Tikely 19 get when you run the following rogram? main) (i stuctem i char namef20 fat sal; = 40 Test Your C Skits (Chapter 4: Floating Point Issues 4 h ‘What should you do to teat the constant 3.14 a afloat? suc emp a0): forlin0;lecait) Qanv | scan ("el ae, etal). } What should you do to weat the constant 3.14 a fog double? |A. Suspicious pointer conversion is Bowing po feats noted a Cannot se sean) fr structures . Strings cannot be nese inside structures What would be the ouput of he following program? Q as 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 iypes of real datatypes available in © and what are the format specifiers ase for for therm? Q 410 By default any real number i ested as ‘float Adouble Tong double epends upon the memory model that you are using Q an poe> mi) it %d50 cso (3,14), szeo( 3.14}, sizeof (2.141) ); } 444 4 Garbage value Garbage value 4810 Exor @ su | The binary equivalent of 5375 is poe A. to1.101110111 B. to1o11 © 01011 B. None ofthe above Q 115 How lars are sored in binary for? 2 Test Your C Skills Q 16 A float occupies 4 bytes. I the hexadecimsl equivalent of each of these bytes is A,B, Cand, then when this floatis stored in memory these bytes get stored in the ordet A. ABCD B. DCBA © OxABCD D. OxDCBA. 47 If the binary equivalent of 5.375 in normalised form is 0100 0000 1010 1100 0000 0000 0000 0000, what would be the ouput of the following program? ‘main() { fost a= 5375; = cher") a; for(iz0sle=3;k4) pr ( 02x", (unsigned char pi) 40.Ac 0000 04CA 0000 0000 AC40, 0000CA 04, poe il Chapter 4: Ploaiing Point Issues Answers: A 41 A Aw B A 43 D A 4 '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 is A A 47 be Test Your C Skills A 48 What causes the "floating point formats not linked” error to occur? ‘When the compiler encounters a reference tothe address of afloat. ‘tse a flag to have the linker link in the leating point eralaior, A ‘oating point emulators used o manipulate oating poinc murmbers, in runtime library funetions like sce) and ao). There ate some ceases in which the reference to the floa isa bit obscure and the ‘compiler does not detect the ned forthe emulator. ‘These situations usually occur during the inital stages of program development. Normally, once the program is fully developed, the ‘emulator wll be used in sucha fashion that the 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) ( fost a=0, "b= Ba; cause emuitortobe inked 2 =°D; suppress wating -varnat used“ ) ‘There is no need to call this Funes A 49 3 from your program. oat byes ef ouble Shyer lf long double 10bytes LE A 410 zz Chapter 4: Floating Point Issues as B A au Use 14¢ A 4122 Use 3.141 A 413 re A 4 B A 415 Floating-point numbers are represented in IEEE format. The IEEE, format 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 mantisa ‘whose most significant digit is always 1. The IEEE format takes ldvantaze ofthis by not storing tis bit at al. The exponent isan Jeger sfored in unsigned biniry format after adding a positive Integer bias Ths ensures that the stored exponent is always positive. The value ofthe bias is 127 for loars and 1023 for doubles, A A 416 Aan ‘Test Your C Skills »_ Chapter 5 Functions Q 61 What would be the output ofthe following program? rman() print ("Sed et, 6); ' re taint =0: ing i(ni-o) reun(s) # ‘est Your C Skills “Chapter 5: Functions Qu ‘Point out the error inthe following code Q 82 ‘What error would te following function give on compilation? {ita int) Missing parentheses in retur statement The function should be defined as int f( int a, fu ) Redeclaration of «| None ofthe above A 2 é B Q ss Ter is a make [nthe following code. Al shea in a smain( ) { any, inthe following function. intas (10,344); inte, ) 1 (it aa, oat { : ‘> 207 retum 10): eta (20); retum (leet) 2a +b); Q se function cannot be defined inside another fuction. 50 Test Your C Stills Q 57 Will the following functions work? (tain) C retum (12(20)); ‘p(inta) i ‘etum (aa); Q 58 ‘Whatare the following two notations of defining functions common ly known as: in (int, oats) ( soma code ) intt(a.b) inca foatb; ( 1 some code") 1 Q 50 ‘Ina function two resurn statements should never occur. “In C all functions except main() can be called recursively, 512 Invally recursion works slower than loops. 53 _Tsittrcthat too many recursive calls may result intostack overflow? es!No> bt ‘many times the following program would print Jamboree"? ) paint \uamboree"); Sin) Infinite numberof times 32767 times (65535 times 2 ‘est Your CSkils 1S: Funtions 3 D. Till he stack doesn’ overtiow A is Answers (Asso, 7 62 A 52 58 cs first one is known as ANSI notion and the seconds known as ighan and Ritchie or simpy, K& Rnottion, A 53 59 Adi the following function prototype in main fea int oat); A 54 5.10 Inspite of defining the Function ) as returning void, the program is tying to collect the value returned by f) im the variable a A 55 bu False. Any function including main() canbe called recursively ‘return stalement cannot be used as shown with the conditional ‘operators. Instead the following statoment may be uscd: a tetum (a> 20710:20); w Test Your C Skills A 513 Yes A 51 Chapter 6 The C Preprocessor Qu Ifthe file to be 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 ofthe following program? _feetne SOR) x") 6 ‘Test Your C Skills © Bror D. Garbage value Q s4 How would you define the SOR macroin6.3 above such that itgives the result oF aas 25, Q os What would be the ouput ofthe following program? ‘eine CUBED) x") main() { inta,b=9; a= CUBE (++) int (“nts ) Q v6 Indicate what would the SWAP macro be expanded toon preprocess: ing, Would the code compile? ‘deine SWAP(2,0,c) (et rman) aa=bbe1:) lntx=10,y=20; SWAP (3, nt) Print (0 xy) ) Chapter 6: The C Preprocessor 2 (Qo ‘How would you modify the SWAP macro in 6.6 above such that tis able to exchange two integers. Q ss Wht the inition ofthe SWAP macro of 67 above? Q 6s In which line ofthe following program an error would be reported? 4, fdelne CRCUMIA](3.14° RR); "What is the type ofthe variable Din the following declaration? Adeline LOATPTR fat * FLOATPTR2,b 38 ‘ess Your € Skills Q on Is itnecessary that the header files should have a extension? Q 612 ‘What do the header files usually contain? Q a3 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 as Cnincusion, where arth header es searched fr? Q 6 Would the following typedef work? ‘ypode! nude |; print (ca at would be the output of the flowing program? "pint MESS"); ld the following program print the message infinite number of js? fine INFINTELOOP wile (1) oo ‘Test Your C Skills main) ( INFINITELOOP. Print (“Grey hare); ) Q 620 ‘What would be the ouput of the following program? ) (a>b2a:b) intx; x= MAX (942,247); A ara SE Q 621 ‘What would be the output ofthe fllowing program? fine PRINT in) print (dl * it) main) i Intx=2,y=3,2=45 PRINT (x); PAINT(y) PRINT(2): ee Q ox ‘What would be the output ofthe following program? er 6: The C Praprocessor 61 “Wetine PRINT int) prin (ot = Hd int) man) tx=2y=s.2=45 PRINT(x); PRINT(y); PRINT(2); ) Q 623 How would you modify the macro of 6.22 such that it ouputs: x=2y=92=4 it (Tips Taps") 625 Define the macro DEBUG such thatthe following program outputs: a Test Your C Skills Chapter 6: The C Preprocessor 63 inte PRINT(,b.¢); DEBUG (x, %d); ers DEBUG (2,92), DEBUG (eh, e}: 61 , me Q 626 62 ‘What would be the output ofthe following program? feelin si) False etn Xt) st) ‘dalne oper mutily A 63 main) i har "qperare = Xs (ope); pints", operame ); 'B, Because, on preprocessing the expression becomes a = (342 243) A 64 doin 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++ * bt+ * bt+ is undefined. Refer Chapter 3 for more details on tis. A 66 (Intt;t=aja=b,b=t:)5 “a ‘Test Your C Skills ‘This code won't compile sine declaration of reannot occur within parentheses A 67 ‘ote SWAP(a, b,c) ct;t=a,anb, bet; A 68 cannot swap pointers. For example, the following code would not compile. ‘dene SWAP(2,B,c) ¢t;1=4,a=b, b="; ) moana: 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 ero. A 610 ‘float an nota pointer to afloat, since on expansion the declaration ‘becomes: Neat ',b; | Chapter 6: The C Preprocessor 65 A 611 No, However, traditionally they have been given a th extension to dentify them as something different than the program files A 62 Preprocessor directives ike Aden, srucure, union and enn dee- Iaratons, ypedef declarations, global variable declarations and ex- ternal function declarations. Youshould nt write the actual code(.. function bodies) oF global variable definition (hat is defining or inalising instances) in header ils. The include diese should He-usedo pul in header les, not oer les. 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 ‘thatthe name ofthe header file is FUNCS H. Phuncan*? $indol_FUNCS ‘iene FUNCS Fal declarations would go here" Herat _ Now if we include this file twice as shown below, it would get included only once Chapter 6: The C Preprocessor or % Test Your C Skills ‘include “goto. c™ A 620 ech poor vm) a sae code") , A 621 A 6s 234 included using <> the files get scarched inthe predefined (can be A 622 hanged) include path. included withthe "syntax in ado 9 Beas ‘hepredfined include path thefles also get searched inthe curent directory (usualy the directory rom which you invoked the com. pile). A 623 Aline PRINT it) pint it) A 616 ‘main() ( 122.923, Nii pis win eg ieee PANT(y): A 617 PRINT (2); , No. Even though the ide fils inthis case (NOTE being undefined) and the if block doesn’t go for compilation errors in it are not Permited, A 618 Mess A 6.19 Yes ‘The rule is if the parameter name is preceded by' a # in the macro ‘expansion, the combination (of # and parameter) will be expanded, into a quoted string with the parameter replaced by the actual argu ‘ment. This ean be combined with string concatenation to print the ‘output desired in our program. On expansion the macro becomes pire = 84x) “The te strings get concatenated, so the effact is pit x= 58x) Test Your C Skill A 624 ‘Yes. The ouput would be TipsTraps. In fact this esulthas been used, in 6.23 above. A 595 ‘ine DEBUG vat, rt) print (“DEBUG var A 626 rt var) multiply Here two operations are being caried out expansion and stringing, ‘Xsir() macro expands its argument, and then str) stingizes A 627 ‘ne PRINT( vat, var, va) pint ("Wart "= "ard" = ed ‘ara"= "6d vat var, va) Chapter 7 Pointers Qu Can you combine the following two statements into one? Can you spit the following statement into «wo statements? harfor "or = (char far *) OxBB000000L; Q is Are the expressions “pir and ++*%ptr same? Q a4 ‘Can you write another expression which does the same job as setptr? 0. Test Your C Skills Q is ‘What would be the equivalent pointer expression for refering the same element as aff] J0AI007) Q vw ‘What would be the ourpr of the following program? ‘man() xan =(12, 181415161: int nth Ha siz (a), tec ( ‘ar, sizok an0]}): ) Qa ‘What would be the output of the following program assuming that ‘the array begins at location 1002? ‘main() intIs1=( 4.2.34, 5.8.7.8, 910,14,12 iy it insu ou Su lO} 1, (D+ 1),°(" (2-40) 419) ) Chapter 7: Pointers Qs ‘What would be the output ofthe following program assuming that “thearray begins at location 10027 ‘mai() int a2]914 =( 12.34, 5.678, gate i { 21.47, 6789, 0.0.0.0 rin ku hu Su "8 79 the following program how would you print 50 using p? in) int al)=(10,20,90, 40,50); char"p char") a; Test Your C Skills Q 70 ‘Where can one think of using pointers? Qm Inthe following program adda statement in the function fn) such that address of o gts stored inj. mran() “ay: seit (ie ) ae von (int) ha ‘add staoment hee *Y ) Q 72 How would you declare an aray of thre function pointers where ‘ech Function receives tivo int and returns afloar? Q 73 ‘Would the following program give a compilation error or warning? main) imta=10,4; wid; jsk=8a; iy ee print ("su "| K); 715 foul te following code compile successfully? ) pint (ie, 71 "Sunda }); m4. ‘Test Your C Skills Answers Ain char "p =maloc (100); No. Spire increments the pointer and not the value pointed by i, ‘whereas ++4ptr increments the value being pointed toby pr. A 74 Co Aw sO Clas eee) A 76 1022 Azz 004 2 2 fer 7: Pointers 25 78 j002 1002 1002 1 79 ("ait *((int") +4); 710 tot of places, some of which are: Accessing array orstring elements Dynamic memory allocation Call by reference Implementing linked lists, trees, graphs and many other data structures 7 72 (“or (in i); 71a > Here no typecasting is required while assigning the value to and ‘because conversions are applied automatically when other inter types are assigned to and from vod * 16. ‘Test Your C Stilis A 714 No. Aneror would be reported in the statement ++ since arithmetic ‘on void pointers is not permitted unless the void pointer is ap- propriately 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 n which header file isthe NULL macro defined, 83 is it that for lange memory models NULL has been defined as ‘and for small memory models as just 0? 84 a's the difference between a null pointer, a NULL macro, the "IINUL charsctor anda null string? 8 ‘Test Your C Skills Q 86 What would be the output ofthe following program? Isthe programming syle adopedin 8.6 good? Q 88 ‘What would be the output ofthe following program? ‘nce ‘so main) ( print ("iS sizol (NULL), seo |*}); Q a9 How many bytes are occupied by near, far and huge pointers? (Chapter 8: More About Pointers 2 Q@ 810 Whatdoes the error*Null Pointer Assignment’ mean and whatcauses this error? Q sn How do we debug Null Pinter Asigmmen enor? Q sn nay ln pce Nall Poa Ast ge og Q a3 ‘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 as Can two different far pointers contain two different addresses but refer tothe same location in memory? 40 ‘Test Your C Skills Q 2 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? Wouta te following program give any warning on compilation? ‘fncude stgo ht on fet pt,1=2550; char ‘po; Chapter 8: More About Pointers 1 Q a9 "What warning would be generated on compiling the following pro- et How would you eliminate the warning generated on compiling the following program? How would you obtain a far address from the segment and offset addresses of a memory location? Q sx How would you obtin segment and offset addresses from a far address ofa memory location? 2 Test Your CSkills Q s20 Ina large data model (compact, large, huge) all pointers to data are ‘32 bits long, whereas ina small data model (ny, small, media) all, pointers are 16 bits long. Q a2 ‘A near pointer uses the contents of CS register (if the pointer is pointing to code) or contents of DS register (ithe pointers pointing to data) for the segment part, whereas the offset pats stored in the 16-bit near pointer Q 825. ‘What would be the curpu ofthe following program? main) ‘charter ‘a= cx00000120 charfar* = oxo0r00020 charfar*c= 000120000; it(azeb) rit (intl Mazz) print ("rh it(b=ec) pend | rialo HY); (a>dakasc&ab>o) print Bye"); Chapter 8: More About Pointers 83 Q a2 ce ctr gn 2020; char huge °b = 0x00100020; char huge ’e= 0x00120000; it(asbaka>ckab>c) ‘rit ("nye") wers A at No A 382 Infiles "stdioh” and “stddet.h” A 33 ‘Because in small memory models the pointer is two bytes long ‘whereas in large memory models itis 4 bytes Tong. ra Test Your C Skills A 84 For each pointer type (lke 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 A ss A nul pointer i a pointer which doesnt point anywhere, A NUL macofs seo eres! the ml plier in source ‘thas a value 0 associated with it, e ‘The ASCII NUL character has al its bits as D but doesn’t have any relationship with the null pointer. ‘The mull string is just another name for an empty string“ A 86 5 A 37 No. Only income of pins shuld NULL and 0 be cas equal, NULL snd ot be ued when ober Lind aoe ‘Se Een tough isin were tsataaycol popes ANS pena dean of e NULL macs Te ).85 “hich nares hatte NULL wl a Wo or puro A 38 21 A 39 “A near pointer is 2 bytes long whereas afar and a huge pointer are 4 bytes long. A 3.10 ‘The Null Pointer Assignment error is generated only in small and ‘medium memory models, Tis eror 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 zerobye in the data segment, At program termina- tion, the four zeros and the copyright banner are checked, If ether has been modified, then the Null Pointer Assignment error is, generated. Note that the pointer may not wuly be null, but may bea ‘wild pointe that references these key areas inthe data segment. A su In the Integrated Development Environment set two watches on the ey memory locations mentioned in 8,10, These watches, and what, they should display inthe watch window. are: *(char"j4aes Botand C++ + Copyright 191 Borland It 86 Test Your C Skills (char‘jo 00000000 ‘Ofcourse, the copyright banner will vary depending on your version ofthe Borland C/C++ compile, ‘Step hough your program using For FT and monitor these values inthe waich window. At the pint where oe of them changes, you fave st exeeteda Sateen tat ses a pointer hat as po been rope ‘The most common case ofthis eos probably declaring = pointer and then using It before alloeting memory fort. For Sample Compile the following program in the small memry made tnd crest include “os ft ‘ince “st0." ncude “sting min) { charpy, “banner banner = (char *) MFP (_08, 4); pri | ‘vanner: is, anna): ‘toy ("The won cup saga"); rit pt = Spe, (voi far) 0); Print banner: is, baner); ) ‘One of the best debugging techniques for catching Null points assignment errors is fo tur on all warning compiler messages. I'the above program is compiled with warnings tumed off, no warning messages will be generated. However, i all warnings are turned on, both the sep) and pring ells using the ptr variable will geneiate \wamings. You should be particularly suspicious ofany warnings that «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 are used fr data, Therefore, a null pointer will reference 0000:0000, fr the base of system memory, andusingit will nt cause acorruption ofthe Key values st the base ofthe data segment. Modifying the base bf systemmemocy usually cases 2systemerash, however, Although it would be possible that a wild pointer would overwrite the key ‘values it would notindicateanll pointer. Inthe tiny memory model, DS = CS =S. Therefore, using a null pointer will overwrite the beginning ofthe 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 or 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 coruption could result in this error being generated. Ifthe pointer used inthe program, ‘statement which corrupts the 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 816 No A a No A sis ‘Yes, Suspicious pointer conversion in function main A 319 Non-portable pointer assignment in function main. A 820 Use the typecast sr = ( char far * ) 0x8000000 ; A 821 include "dos main) har ‘seg = (cha) 18000; ‘har ‘of= (char) 0x8000; “Chapter 8: More About Pointers 89 charfar’p; a MK FP (209,011); char far) oxBep00000 seg: ( char") FP_SEG (ser); of | char*) FP_OFF (ser); 8.23 sat 825 Bye 4b and refer to same location in memory sil the is three is fil because while comparing the far pointes using == (and !=) Full 32-it value i used and since the 32-bit values are diferent 1 fal. The las ifhowever gets satisfied, because while eompar- using > (and >=, < <= ) only the offset value is used for parsion. And the offst values of , band c are suc that he last liom sate. 0. Test Your € Skills a se Chapter 9 Hallo Hi Arrays Hello a Unlike far pointers. huge pointer are “normalized” to avoid the strange behaviour asin 8.25 ahove. A normalized pointer is a 32-bit pointer which has as much of its value in the segment address as possible. Since a segment can sire every 16 bytes this means that on the ofset will only havea value from 0 19F. Huge pointers are always kept normalized. As a result for any given memory address there is Bes i ash ed be nel paw ‘only one possible huge address - sezmentofst pair fort prin ("aPed e, stzeof (a), steal (BJ) ‘int ("ted Se’ sizeof (a), sizeof (*B)); 92 the following statements would arr[3] and ptr13] fetch te same haracter? * a an) = “Supe” = "Supe; 98 he statements in 9.2 does the compile fetch the character ar7/3) id pr 3 nthe sare manner? 2 Test Your C Skills Q 4 ‘What would be the output of the following program, if the array begins a adress 12007 rain) ( inant] ={2,3,4, 1,6); it "68 at ar, iol at) ); ) Q 95 Does mentioning the array name gives the base address in all the contexts? Q 96 ‘What would be the output of the following program, ifthe aray bein at address 654867 ral) int ant} = (12,14, 15,23, 45) ; print "6496" a, Bar); 1 Q 97 ‘Are the expressions arr and arr same for an aray of 10 integers? Pr y ‘Chapter 9: Arrays 93, Q v8 “What would be the output of the following program, ifthe array begins at 654862 main) i int an} = (12,14, 15,23, 45); ret ("uM r+ 1, Barr+ 1); 1 Q 29 When are char af J and char *a weated as same by the compiler? Q 210 ‘Would the following program compile successfully? mman|) charal]="Surstok prin ("nts "a, p); } Q on What would be the output ofthe following program? man) o. Test Your CSkills { feat af}= (124,23, 45,67): IC Q 22 \ [A pointer to a block of memory is effectively same as an array, Q 913 ‘What would be the outputof the fllowingprogram fthearray begins a1os472? ot) ‘maby 1.234 4321. 7880 ii 1 PAM ort Beet Q ou ‘What does the following declaration mean fetta); Chapter 9: Arrays 95 Q 0 If we pass the name of a 1-D nr array toa funetion it decays into a pointer to an int. IF we pass the name of a2-D array of integers to function what would it decay into? % Q 916 How would you define the function 1) inthe following program? Int anf MAXROWIMAXCOL]; fun( ar); Q on ‘What would be the output ofthe folowing program? rman) 1 int aa] =( inet p= Rall). fun, 882) } fun iin) print tsp) 6 Test Your C Skits Chapter 9: Arrays 7 Answers When array name is wed with ce operator ‘When the aray name san operand the & epee Ast A 96 12 ia A 92 Yes A 93 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 pirf3 it generates the code to start at location stored jn pir, dd three tothe pointer. and finally fetch the character pointed Inother words, arr[3}is three places past thestartof the abject named ‘rr, whereas piri] is three places pst the object pointed toby por A 94 1200 10 A 95 No, Whenever mentioning the array name gives its base adress tis ‘tid thatthe array has decayed int «pointer, This decaying doesn’t lake place in two situations: 65486 65486 pA 97 No. Even though both may give the same adresses asin 9.6 they mean two different things, arr gives the address of the frst nt, whereas arr gives the address of aray of nts, Since these adresses happen 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 a new string 0 @ pointer but not 10 an amy, A au oe Chapter 10 a Strings A on 5180 65486 : fo —Q 101 ‘What would be the ourpu of the following program? ris a pointer 1 an aray of 10 imegers A 915 iain) pri (5+ Facile); Ui decays into a pointer to an array and not a pointer toa pointer. ae Bei A 216 Bf tenance Es Map tester i 4 Q w2 What wou beth output of the following program’? fun (int (“ptr MAXCOL] ) (ptr is pointer to an array *) ‘ main) a ( chars chars Sates if(ot 1) 1 i print “nqual”) ; 100 est Your CSkills int ("oUrequa) Equal Unequal Entor None of the above @ ooee 103 ‘What would be the output of the following program? a Print (Sc, abode); A. Enor Bd ce D.abedefgh Q ws ‘What would be the output ofthe following program? man) A. Brot BL Strings ©. Cannot predict Chapter 10: Swings 101 D. None of the above Q ws ow would you output \ on the screen? Q v6 ‘What would be the output ofthe following program? mein i charch= 8; rnd, sizoo | ch), sizaot|'8) }: ) ' 1 e 2 pnee Q 07 ‘What would be the output ofthe following program? rain) rin | ed 0c, Siac (3), zea (3), Sze0f(3)): pose 02. ‘Test Your C Skills Q ws Is the following program corest? rman(| char ‘sir = “Uni char‘st2="Fon; ents, st); } 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? ‘main() { char st] ="Keep nda Beautiful, emigrate!” chars stepy (st, st): rit "ss st): } ‘spy char, chars) { while(’s) 1 Chapter 10: Strings 103 Q wn Can you compact the code in spy) into one line? Q 12 ‘What would be the output ofthe following program? mman() ‘ char‘ }={Freg' ‘Do, Not, "Die, They’, "Cro"; it ("bd epost) sizot s])); 1 Q ws How would you find the length of each string in the program 10.12, above? Q mu ‘What isthe difference in he following declarations? sos ea Your Ste Chapter 10: Srins os Q wis A 16 ai dig bag ra si Seo erst B dee eee euie (inden ae ae te unit, A 107 Answers e A ior A ws © sete Se ee ke Be saroumsh cs Bat us euer Cpe henkosistele A 1: epapyae riya B A 109 ‘main( ) A 10s ; crs" c Sarat For oe, ‘str = streat (str, st); A ins pir who) J iene omelet emery tt character string has been stored, This would result into overwriting. A 10.10 Wat ieetdton conocer nai Tee fea geatdl ue ee eget ee ) ten which would be unsafe. gents) A 101 A ws print in") ‘teoy (char char’s) { 106. Test Your C Skills while (HE ="sH+) 1 A 1.12 R2 A 1013 main) char stl] = (Frogs Di, They’, “Crakt iti; lor (i=0;]-<=5;i¢4) ‘ Print (“nie 6, sr, ten stf]})): A 10.14 Here a is an array big enough to hold the message and the "0" following the message. Individual characters within the array can be changed but the address ofthe array would remain same. On the other hand, p is a pointer, initialized to point to a string constant. The pointer p may be modified to point to another string, butifyouattemptto modify the string t which ispointing the result, is undefined A 10.15 A sting can be processed only ona character by character basis Chapier 11 Structures, Unions and ~—Enumerations” ud at isthe similarity between structure union andanenure U2 fou the following declaration work? (Can astrcture contain a pointer to itself? Q us int ou the eror, if any in the following code, 108 Test Your CSkils “Chapter 11: Sirctures, Unions and Enamerations 109 Donte Q a7 in ata NODEPTR inks Would the following code work? | /NODEFTR: “ile aloe» ara ‘suct emp itlen; ow wil you eliminate the problem in 11.8 above? ene Q 10 eS, { Point out the error, if any, in the following code, ‘void modty (tut emp); stuctem 1 char nanef20|; int age i me) struc emp e= ("Saray 35) madly (82) RES tae orien) yd ne") ‘sup (poname |: poage=poage +2; char newnamel}="Rahul | struct emp ‘p= (stuct emp") male (sea truct omp )- 1+ sion (nowrame) +1); F en (newname siropy ( poname,newname ); Bp eH rk pin 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? Chapter 11: Structures. Unions and Enumerations ut uo est Your CS snl enpea= Q n0 etme) (Can you rewrite the program in 11.8 such that while freeing the ‘memory only ane cil free) would suffice? Qo un ‘What would be the output ofthe following program? rab ‘atelemp "Davi 28); print (ase ota); ) Q urn Point eu the error, if any, inthe following code. man) ( stu omp pin | "The stucures are equa"); ) Q us How wouldyou check whether the contents oftwo structure variables, are same or not? Q un How are structure passing and retumning implemented by the com= piter? Q us How can readfrit sroctuesfromfo data les? Q wu Ifthe following structureis written toa file using fwrite),can fread) read it back successfully? FLE"p; fart ( Be, sizeo(e), 119); i ‘Test Your C Skills Q mi ‘Would he following program always output the size ofthe sractare as T bytes? sinc ox char ch ii: long ina: K Q 18 ‘What error does the following program give and what is the solution fori? man) { suc emp { char name); float sal; Fe su emp off); shee9;l44) scarl (8%, f.name, esl): ) @ nw ‘How can I determine the byte offset ofa field within a structure? Chapter 11: Structures, Unions and Enumerations 3 Q 120 | ‘The way mentioning the array name or function name without [Jot () yield their base addresses, what do you obtain on mentioning the ssructurename? Q un ‘What i main) returning inthe Following program, struct ransacon ( intsno: char dsc); char co foal amount; _ Heres he main program." ie ca) ‘tet fensacon scant ( "ad is ie Wf, ts, ides, Bt, BLamount) rit ed Sr no, tes, Lt, Lamaunt) ' Q ux ‘What would be the output ofthe following program? ‘man() 4 Test Your CSkils (Chapter 11: Structures, Unions and Enumerations 1s catagory : 5; ey @ nx Vi Le eee ee eee 8 ) of ype int can we fcely intrmix ther with other intcgrl pes, ‘without eros? 1139 e Q 128 ‘Whats the difference between a stricture and a union? Q uma Is it necessary that sizeof al elements ina union shouldbe same? ; Q 125 Point out the eror, if any, in the following code, Is there an easy way to print enumeration values symbolically? Q 12 ‘What isthe use of bit fields in a structure declaration? Q 130 (Can we have an array of bit fields? nane, wae |: pint ("ds pole >a al A uu DRAVID ‘When a structure is assigned, passed, or returned, the copying isdone ‘monolithically. This means thatthe copies of any pointer elds will Point to the same place asthe orignal. In other words, anything inted 1 is not copied. Hence, on changing the name through €2.1 ‘automatically changed en A un Structure can'tbe compared using the bul in ==and ‘=operations This is because there is no single, good way for a compiler to 120 ‘Test Your C Skils implement structure comparison A simple byte-by-byte comparison ‘could fail while comparing she 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 Amounts of repetitive code for large structures. Also, any compiler- ‘generated comparison could at be expected to compare pointer fields appropriately in all cases; for example, i's often appropriate ‘o compare char * Fields with tmp raher than with A iis sania ame ‘har le iiago structemp et = ("Dravid 28); struct emp e2 scat ("Ms St, 2, B2.age i (sictomp (0, 2) —=0) Print "The stucres ae equa eke print "Te stuctures ae urequat , stutanp (srt amp, stuet omp i ) it( stomp (xn, yn): (age = yage) return (0) retum (1) } (Chapter [1: Structures, Unions and Enunerations 2 Inshort, if you need to compare two structures, you'll have fo write {your ov function 10 do so which carties out the comparison field by Tiel A 13 ‘When structures are passed as arguments to functions, the entire Structure is typically pushed on the stack. Te 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 anextra,complier-suppied ‘hidden’ argument ‘othe function A 1115 To write out a structure we can use frite) as shown below: ite (8, sete), 1.1): ‘where ¢ isa structure variable. A comesponding jread{) invocation ‘an read the structure back from a file. On calling forte) it writes out sizef{ e byes from the address e. ‘Data files writen as memory images with fwrit(), however, will mot be portable, particularly if they contain floating-point fields or pointer. Thisis because memory ayqut of structures 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 he 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 betwoen machines. re ‘Test Your CSkills A m6 No, since the structre contains a char pointer while writing the ssruetue othe disk using fwrite) only the value stored in the pointer ‘r would get writen (and not the sting pointed by it). When this structure is read back the address would be read back but itis quite unlikely that the desired string would be present at this address in emery. Aim No. A compiler may leave hols in structures by padding the frst, ‘char inthe structure with another byte just to ensure thatthe integer that follows is stored at an even location. Also there might be two letra bytes after the integer to ensure thatthe long integer is stored fat an address which isa multiple of 4. Tis 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 witha pragma, but there is no standard metho. If you're wortied about wasted space, you can minimize the effects ‘of padding by ordering the members of a 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‘Floatng point formats not liked. What causes tis error to ‘occur? When the compiler encounters a reference to the address of ‘loa, it ses flagto ave the inke 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 lke scan!) and atoff. There are some cases in which te eference tothe floar isa 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 eralator. To force linking of the floating point emulator into an application, {just include the following function in your progran it LinkFoat (void) oat a= 0, b= 8a; "cause anultortobe Inked) ="; suppress warning -varnot wed" ) “There is no need to cal this funtion from your program. A 1119 ‘You can use the offset macro given below. How to use this macro has also been shown in the program, Actin otse{ype, mem) (int) char“ (ype *)0)- mem «(chr ('yee*)0)) a seta char name) Intage; oat sal 124 ‘Test Your C Skills floetclage = oft (struct, go) rn (8, ofstlege); ofisetosal =e (struct sa): prin (ic, sos): } ‘The output of ths program would be ois 7 A 120 ‘The entire structure itself and notits base adress. A 121 ‘A missing semicolon atthe end ofthe structure declarations causing ‘main() to be declared as returning a structure. The connection is dificult o see because ofthe intervening comment A 122 size =2 Chapter 11: Structures, Unions and Enuerations 125 Since we have used 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 i being reported as 2 bytes A 23 ‘A union is essentially a structure in which all ofthe fields overlay ‘ach other; you can use only one field a atime. You can also write to one field and read from another, to inspect atype’s bit pattems or ‘nterpret them differently. A m2 No, Union elements can be of different sizes. Ifso, sizeof the union issize ofthe longest element inthe union. As against this tho size of a structure isthe sum ofthe size of its members. Tn both cases, the size may be increased by padding A 1135 ‘The ANSI Standard allows an initializer forthe first member ofa 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 adopied yet. IF you still want (0 inialise different members ofthe union then you can define several ‘variant copies ofa union, withthe memiers in different orders, so that you can declare and initialize the one having the appropriate ist ‘member as shown below. union a ( mm; 126. ‘est Your C Skills tion 21 = (512): unin 22 = (0,2): ) A 126 “Theres hardly any difference between the two, except that define hha a global effect (throughout he fle) whereas an enumeration can have an effect local to the block if desired. Some advantages of ‘enumerations ae that che numeric values are automatically assigned ‘whereas in efi we have texplicitly define them. A disadvantage is that we have no control over the sizes of enumeration variable. 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 stractures having several binary flags or other smal fields. Not thatthe colon notation for specifying the sizeof a field in bis is valid only in structures (and in unions): ‘you cannot use this mechanism to specify the size of arbitrary variables. A 1130 No Chapter 12 Input/Output Q 2 Wha would be he ouput he llowing ogra? main( ) { int a=250; print (ote, a): ' Q 22 ‘What would be the output ofthe following program? main) 130 Test Your C Skills (Chapter 12: Inpua/Ouaput 131 Q ws Q ws In the following code Pint out the ecrr, if any, inthe following program, ‘incude Fioclude ‘sido mmain() ao ( FILE“; ung char = fopen ia"); FE": ‘ {p= lopen ("wa "°): “fp points to tm) ‘A. The fist character inthe file a inet oat): ® B.A structure which contain a char pointer which points tothe first character in the fle © Thename of he file D. None ofthe above ) Q ws Q 26 ‘Ifa fle contains the line “Lam 2 boy\vin” then on reading this line Point ont the ero, if any, inthe following program, error, if any, inthe following ito the array str using fgets) what would sircontain? tia 60 — A. “Tamaboo¥ion f B“Tamaboy 0" cetera © “Tama boyinio™ FLE'p: D. “lamabey” fp =fopen “ia 1) Q 2 while ((ch = getc (fp )) l= EOF ) Print ("9uc", oh); Point out the error if any in the following program, ose); ARES 133 2 Test Yu ile hoe 12: gu re Q 2.10 os Point out the error in the following program. fp=fopen ( rial) 5 . fac sec) feo ‘dose (Ip): wy : FILE “ip: oer: @ ws “0 Drs tgen ar: ‘To print out aand b given below, which priny) statement would ‘wale (tea! (1)) ae gets (str, 80, fp) ; float 4; puts (sir): Sal , ‘Aelose {2 A pint. 8): ! Bo pometoeteeta € femtcatraties). basi B pomeser a6), Point out the error inthe following program. Q 2s tect ‘stsoh" “To'scan and b ives elow which can) sic Yel veo? a toate arch; bled in fear" a): A sean (" GF", a, Ab); sean ("et Bo sean @LEGLP. a, &b) ie scan CRFSLE. a. 8b ) D. sant ("FIP ab); 134 ‘Test Your C Skills Q vw ‘What would be the output ofthe following program? mman() 1 it (“nS 66%"); ) @ wx Point ou the error, ifany, inte following program? ncude sth rain) ( FILE; {ip =fopen ("inca w"); f(t) if); {ose (fp); Q wu ‘Would the follwing code work? yes, what would be the utp? ‘main() { intn=5; pint ("n= n,n): Chapter 12: Inpu/Oupus 135 Q 25 ‘What isthe * in the pringf)of 12.14 indicative? Q ws (Can we specify variable fleld width in a scanff) format string? Q 21 ‘To tackle a double in pring) we can use %f, whereas in scan) we should use 9 Q wis (Out of feet) and geist) which function is sae 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 toa fle without an intervening call to flush), fuek() oF rewind). 136 Test Your C Skills Answers A wi BOF has been defined as Adefine FOF 1 in the file “sido. end an unsigned char ranges from 0 to 255 hence when EOF is rea from the file itcannor be accommodated in ch Solution isto declare ch as A 2s Noeror. A 26 ic Chapier 12: Input/Output 137 A wz Instead of 20 use 20L since foeek) needs a long offset value. A ws A. Icis possible to print a double using Ef A no D A 2.20 “The last ine from the file "ial" would be read twice. To avoid this, se: hil (gp (st 80, fp) = NULL) puts (8); A iu You would not get a chance to supply character forthe second scan statement. Solutions to precede the second sean) wth he following statement ‘sh stn) would lush out the enter hit forthe previous scanf])tobe lashed ‘ut from the input stream, ie. keyboard. 138 Test Your C Skills Chapter 12: Inpur/Ousput 139 A 22 A 2218 oe fgets), because unlike fgets), gets() cannot be told the size ofthe ‘buffer into which the tring supplied would bestored. As result there Yar teas is always a possibility of overflow of buffer. ‘he path ofthe flename should have been written as "e\clrial”. A wis Yes. m5 A 215 1k indicates that an int valve from the argument list wil be used for ‘eld width. In the argument list the width precedes the value to be printed, In this case the format specifier becomes %5d. A 1216 1No.A‘"”inscanf forma sting after a% signisusedforsuppression ‘of assignment, That is, the current input field is scanned bat not stored, A wiz True A 219 False A 1220 Tre Chapter 13 Command Line Arguments Q 131 ‘What do the the“ and ‘v" in arge and argy stand for? Q 132. ‘According to ANSI specifications which s the correct way of declar- ing main() when it receives command line arguments? ‘A. main (nt arge, char argv) ‘B. —main( argo, argv) int arge ; char argv]; ©. maint) ) D. None ofthe above Q a ‘What would be the output ofthe fllowing program? int arge ; char Yargv(): P sampla ‘man {int age, char "arg. 12 Test Your C Skills ( ange 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? ahd sae et) rin (4, arglae] Q 135. If the following program (myprog) is ran from the command line as myprg 1.23 ‘hat would be the output? man (Fea der‘ap) int; for(i=0;icane;b+) yeaa: Q ns. {fthe following program (myprog) is ran from the command line as Chapter 13: Command Line Arguments 143 imypog 1 28 what would be the output? nin (it age, ar“) Dia: |r) + argv + arg); et ("5 {f the following program (myprog) is run from the commandline as mypreg 1 23 what would be the ourpur? pa (rane lr‘) 1a Test Your C Skill ee Q 18, ‘Would the following program give the same output at all times? main(int argo, chat aro) { siepy {rg helo®) siepy are), ‘good morning’): pres ae se); Q 180. If the following program (myprog) is run from the command line as yprog one two tree what would be the output? eer kta Q 3210. Ifthe following program (myprog) is ran from the command ine as yprog one wo tree what would be the output? Chapter 13: Command Line Arguments 145 rman {int arg, carro) rin ("S44 ar) ) Q 0 “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 D, _Iemay vary from one operating system to another Q 2. What wil the following program output? rman (it arg, char “rg ena ‘er )) { ini for(int; args) ait ("68 * om) List ofall environment variables List ofall command line arguments Enor NULL, pope is est Your CSkills rogram (myprog) is run from the command line as what would be the ousput? an (bt see) ints for(int; Large) in (av); Ate 1B. Listorall files in the current directory ic D. None ofthe above Q 10, If the following program (myprog) is run from the command line as ypreg *e ‘What would be the ourput? ste cim m1)) inti for( ares) rin (65% an) Chapter 13: Command Line Arguments uy fF all. files inthe current directory pom> [None ofthe above Q 26. ‘If we want that any wildcard characters inthe command line argu- ‘mens should be appropriately expanded, are we required to make any special provision? If yes, which? Q sx, Does there exist any way to make the command line arguments availabe to other functions without passing them as arguments tothe function? Q@ 8 [the following progeam (myprog)is run from the command line as rmyprog Jan Feb Mar ‘what would be the output? nce "dosh min() fant) 148 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 ‘ag ) | ee aoa: A. MYPROG B. CABCITUCSIMYPROG ©. Enor BD. cxpevtucs, Q 1320 Which sancasy vay texraetmyprg fom he opto program 13.19 above? a Q 1321 Which ofthe following is true about argv? Itis an aray of characte pointers Its pointer ton array of character pointers itis an array of strings A B ie D. None ofthe above Chapter 13: Command Line Arguments 149 Q we Ifthe following program (myprog) i run from the command line as myprog menday tuesday wednosday thursday what would be the output? ee he (~arge > 0) print ("8 "s4rge) ‘A. myprog monday tuesday wednesday thursday B. monday tuesday wednesday thursiay CC. myprog tuesday thursday D. None ofthe above Q 13.23. Ifthe following program (myprog is run from the command ine as prog tay Westy sunday what would be the output? tain tg, char ary }) 1 (eu: Am Bef, CC myprog, 10 Test Your sits Chapter 13: Command Line Arguments 1s) >. idey ey By Q 1524 Ifthe following program (myprog) is un fom the command line as ryprog tay tuesday sunday ‘what would be the output? ‘main(int rg, char arg) it (oe) r A. B Cmyprog, D. friday Q 1325. Ifthe following program (myprog) is run from the command line as, iypreg fda tuesday sunday ‘what would be the output? ‘main int rg, char "erg }) | arama: Ar Bet Q@ 1326 Ifthe following program (myprog) i run from the command line as mypreg fiday ueseny sunday ‘what would be the output? main (it stein char ‘agv}) hie szeotarge) print (8 xg -szcoary | ‘A. myprog friday tuesday sufiday 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 et Your € Ste (haste 12: Command Lin rgumens 133 CASAMPLEEXE ie A 14 ze Ne A ne A ns F cowvrrociexe 123 oe A 136 ; 3 A 13 A ia7 4 Wen at) eso ons arg 8 nmr icant dso are {ergio1 ning name) sn eee A na “ s A ns A no Ye. Comite rogram mpg wat This compiles te fe mpg an nk withthe werd re Sipusion odie WILDARGS.O8), fen rn he sling ec SShabic ie 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.OBI, you can ‘modify your standard C?-LIB library files tohave WILDAROS.OBI linked automatically. To achieve this we have to remove SETARGV from the library and add WILDARGS. The following commands will invoke the Turbo Librarian to modify al the standard library files {assuming the current directory contains the standard C libraries and WILDARGS.OB)) {ib os setargy witiargs ib ce -sotargy wiargs ‘i cm -otargy aiargs ‘ib ot setargy ewidergs Wb oh star swigargs A 1317 ‘Yes, Using the predefined variables _arge, argv. A 13.18 ‘CAMYPROG.EXE Jan Fob Mar A 219 B A 1320 Fncude ‘deh main(int xg, char ‘ara }) char die, df, name ext]; prin (argv): {nspit (argv) ve, ame, ext); Chapter 13: Command Line Arguments 155 } A A A ae ae ee > print ("ters dive, de, name, ext); 1321 13.22 13.23 1324 13.25 13.26 Chapter 14 Bitwise Operators Qu What would be the output ofthe following program? man) inti=92,j=0020, km; i | ed Wd SLL); 323232320 oo000 032323232 3232323232 Q uz ‘What would he the output ofthe following program? a unsigned int m: yne> 158 ‘est Your € Skills Chapter 14: Binwise Operators 159 rn, -m) ; faz? A fe print ("ox ox x Mx Mx Ex 0b 6, 4,61); B00 } car D. data Q us ‘What would be the oupot ofthe following programm? ‘main() None ofthe above Q us Point out the error in the following program, pat) unsigned int, 2.64 Dao=d= Q us To which numbering system can the binary number 1011011111000101 be easly converted to? Q us “Which bitwise operator is suitable for 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 putting on a particular bitin a ‘number? Q us (On left sitting, the bits from the left are rotated and brought tothe right and accommodted where there is empty space on the right? ‘ Wo Tet our € Sil Chater 14: Bie Operator 161 Q u0 ane fatlsoe Tie) Letsitings umber salvay eqaaleatomulelyn tbe aera Hosa) ie) Q un ‘Left shifting an unsigned int or char by 1 is always equivatent to ‘mulplying itbe 2. Q urn ‘What would be the output ofthe following program? main) i unsigned char = 0380; int (ice 1); ' Ao B 256 C100 D._ None ofthe shove Q un ‘Whats the following program doing? main() i Uunsgned int = {x01 02, 0304, x08, x10, 0320, 340, 0); ‘unsigned char; Putting off ll bits which are on in the number n ‘Testing whether the individual bits ofn are on or off This program would give an error None of the above pomp Q uu ‘What does the following program éo? main) ( chat*s; fun (128.2); rit "ine ¢) ) ‘un unsigned ine runt base) sialic char buf] har rs pir Abu [sizeo (but )-1]: ‘1234567B6abede' num % base) rum = basa: 162 Test Your CSille Chapter 14: Bisse Operators 163 ) whe (rum <0); { lg it un; rout: inno; ) scan (i, num) for(;rums um >> 1) ‘A. conversa munber to gven base B. It givesacompilatoneror it(rum at) None of the above eos ) iar pa ‘ene HARSZE 8 A. _Iteounts the number of bis which ae on in the number num. Alin MASK) [1 <>); int ont ‘0000 ‘0 Q 10 Inthe statement expression! >> expression? if expression! is a signed integer witht lftmostbitsetto I then onright-shiftng itthe pape Hogar ee dean sete result of the statement would vary from computer to computer. Q 120 ‘What does the following program do? rman) { unsigned intr ini; sean (“0% num) fer[i=0;i< 16;i+4) pr ("ed (num ‘ypédal unsigned ang int uly unsigned logit x,y Q 52 ‘Whats the type of compare inthe following code segment? Aypadel int (pot char char*) itoun compare: Q ws What are the advantages of using ypedefin a program? 170 Test Your C Skills Q 4 Is thete any differnce in the define and the rpedefn the following code? If yes, what? ‘ypedet char” sting feline sting. dchar* sting tt 2; sting 689, sh Q ws tnpedefs 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 6 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 while using syperdef? Chapter 1S: Subileties of ypede im ‘ypodel set employe “pr ust omply ( char namel2) intage; nest; i Q ss ‘There isan error in the following declarations. Can you rectify it? ‘yposet set ( inten BPTR int; yAPTR; typedet tt ( ined; APTR inka y-oPTA; Q so ‘What do the folowing declarations mean? fypodel char ‘pe; Iypede fa) Typede ‘ibe ‘pede pp tpt) ‘npedel be ‘Pippo: Bip aN; rest Your Chis i Test Your Sills Chapter 15: Subletes of ypedef 173 Q 6.10 Q uu would you define «[NJ in 15.9 above without using typedef? ee eee gue In the following code is p2 an integer or an integer pointer? Q wn pc itr ptr pt p2s, Imre the fllowng cod sng pede wers srt ta; oat at A 1 Stacie eh Sree Yes hi trctrote r= adn *) mac (sl (st rte): A 2 6 & Its primero fancon whi ceive ws Sara pl sad Se Ise fellowingdecaion scepbl? Bo ong, ore EE ‘There are three main reasons for using npedefs: peop (2) Temakes writing of complicated declarations a lot easier. This Q 55 helps in eliminating a Tot of clutter inthe program, (b)__ Ithelps inachieving portability in programs. Thats, if we use ‘ppedefs for data types that are machine-dependent, only the Inthe following code what is constant, por the character itis pointing ‘ppedefs need change when the program is meved to a new to? ‘machine platform, : (@) _Ithelpsin providing a better doumentation for a program. For ‘ypodel char“ chap; ‘example, a node ofa doubly linked list is beter understood as const char p pirolist rather than just a pointer toa complicated stracture. 18 est Your C Sills A 154 Inthese declarations, «1,52, and s3 ae all eated as char *, but sis treated asa char, which is probably no the inetention A 155 Te A 156 [A typedef declaration cannot be used until its defined, and in our ‘example itis not yet defined at the point where the link field is eclared. ‘We cam fix this problem in three ways (@) Give the structure a name, say node and then declare the ink Field asa simple struct nade * a8 showin below: ‘ypede stustnode int data; struct nde }"NODEPTR: (0 Keeptherypedef declaration separate from tne ructre detin- 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 field: ‘ypodelstuct rode "NODEPTA; st nado ( intdata; [NODEPTR ink The problem with he code isthe compiler doesn’t know about BPTR ‘whe itis used in the first structure declaration. We ae violating the tule that rypede declaration cannot be used until it is defined, and ‘nour example its not yet defined athe point wher the link! field is declared, ‘To avoid this problem we can define the structures as shown below: siusta c int 5 strut ink h stuctb Inte; struct Tika; 176, Test Your € Skills Chapter 15: Subteties of pede 7 h A 9 ‘patel sucta"APTA: pe isa poimerto char, ‘peel tut °8PTR; fe is funtion reurning pointer to char wipe ispointertoa function ering poitertochar The compiler can accept the Feld decaraton srt per within fotpe isa fontion rewmning pointer to function sirut a, even thoogh it hes not yet heard of sruct (which is returning pointer to char “incomplete” a tht pint). Occasionally, itis necessity to precede Pofpe isa pointer to function returning poiner 0 this couplet withthe fne fantion turing pointer to char fp aN isan aray of N pointers fo function returning std; pointers to funetions returning pointers t0 haracters ‘This empty declaration masks the pairf rvctae declarations (iin a iner stops) from a diferent struct b in an outer seope. After declan te two scr we can then delve the pede pase separately as shown above char“ aNDCIK) Altematvey, we can also define the ypedes before the stature ine MAX 128 main() i const int max = 128; har araymay); char stingMAX] array( = sting = Print (Se "ary, stint); Chapter 16: The const Phenomenon Q us Point out the error in the following program. char youbufl] = "Zenckewiz"; Q 67 Point out the error in the following program. a) char myout |= Zanzibar’ ‘cons char const p= "Helo"; 181 182 Test Your C Skils (Chapter 16: The const Phenomenon 183 pie meas neh) ‘how: ; conettar*) hat‘ i) ) Q@ ue corel ha“) ( rot Hela What does the following prototype indicate? spy | char “arg cont char ‘source ) Q 69 ‘What does the following prototype indicate? const char change (car nt) Q 15.0 Point out the error in the following program. main) een et char*pr=tun) pence} ‘ ‘ou Yet Q wn Is there any error inthe following program? } Q wie Point out the error in the following program, ea const char un) wage) ) const char "un() t ) Q@ wis ‘What do you mean by consteorrectness? Q wu What would be the output ofthe following program? return Heo! rman) ( 184 Test Your C Skills | Chapter 16: The const Phenomenon = ‘const intx=5 ; { ini: canst =7; pies: ii" consig= ak; pex=10; pind °9); pease ) Avie Q wir B 0 © Enor Whats the diference inthe following declarations? Di Garbage valve cone car's; Q 6.15 erent’ What would be the output ofthe following program? Q 1618 na ‘What is the diferencein the following declarations? emstintx=5: coratchar* cont; ae er cher cnst* const; Q 15.19 Is the following a propery writen function? not, why not? Aes B. 10 int fn (cone inin) © Error D. Garbage value an azn'n; Q we rotum a: Point out the error in the following program. nan) 186. Test Your Sule Chapter 16: The const Phenomenon 137 Answers A 167 A 161 [Nowhere other than through initialization can a program assign a valu to a cons identifier. x should have been initialised where its declared. A 162 A A 163 A A 164 “The dimension of anaray mustalways bea positive non-zero integer constant which maxis not A 165 ptr pointer is constant. In pir = yourbuf the program is trying t0 modify it, hence an error. A 66 ‘ptr can be modified but not the object that i is pointing to. Hence _prrisaconstant pointer toa constant object. We can neither modify ‘pr norte object itis pointing to. A ws ‘We can modify the pointers source as well as target. However, the ‘object to which source is pointing cannot be modified. A 69 ‘The function change() receives 2 char pointer and an int and returns pointer toa constant char. A 15.10 ‘Waring: Suspicious pointer conversion. This occurs because caller fl retuns a pointer ta const characer which is being assigned (0 pointer toa non-const, A wu No A 16.12 Fun )retuns a pointer to const character which cannot be modified, A 16.13 + 188 ‘Test Your CSkills ‘Aprogramis ‘constcorrct’ifitnever changes a more commonterm is mutates) a constant object. A 16.14 B A 115 cS A 1.16 ‘Waming: Suspicious pointer conversion. kcan be pointed ro only by pointer toa cons; q isa const pointer. A 1617 ‘There is no difference. A 1.18 ‘There is no difference. A 16.19 Since fn() would be called by value there is no need to dectaren as ‘aconitsince passing by value already prevents an() from modifying Chapter 17 Memory Allocation Q m4 ‘What would be the output of the fallowing program? rman) { cha: ha "fun stint) ri (88) ) chat un() char bute) -ttpy (buf, "RAM Rarely Adequate Memory"); retum (bull); ) Q 2 ‘What isthe solution forthe problem in program 17.1 above? es Tes Yur Si Chg 17: Menor Alain 1 ssa 300.4 @ ns rat Doe ha any ahr lain rhe ein 7.17 upc 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 to access any element using 2 subseript, as in alii Q How would you dynamically allocate a 2-D array of integers such that we are able to access any clement using 2 subscripts, asin arrfl[jP Also the rows ofthe aay should be stored in adjacent ‘memory locations Q ws How many bytes would be allocate by the following code? ‘ncde “alc ht ‘efino MAXROWS P int (*) DMAXCOL) malo (MAXROW" size (*p)); ) Q 179 What would be the output ofthe fllowing program? cldoaloctt ‘define MAXFOW 3 ‘afna MAXCOL 4 pa it (pIMAKCOL|: int(* )IMAXCOL}) mate (MAXROW * sien (*p}) Brit (“ed a, stoop), size (72); t Q i410 Inthe following coge pis a pointer toan eray of MAXCOL elements, Also, malloc allocates memory for MAXROW such atays. Would these arrays be stored in adjacent locations? How would you access the elements of these arrays using p? ‘dene MAXROWS tetine WAXCOL 4 main) i int Int ("beacons 12 Test Your C Skills = (nt(* JMAXCOL])maloc( MAXROW *sieot(‘p)) ) Q wu How many bytes would be allocated by the following code? elude ‘alloc ‘Heine MAXROWS #tefine MAXCOL 4 at) in ‘p)MAXCOLIMAKROW: B=(nt(*) NAXROWIMAXCOL malo (tee (*p)); Q re How would you dynamically allocate a3-D aay of integers? Q m8 How many bytes of memory would the fllowing code reserve? ‘cu ‘alloc? main() ( inp: =(in*) mateo (286"256); (p==NULL) Print (“Alot fal) Chapter 17: Memory Allocation. 193 Q 4 How would you freethe memory allocatodby the following program? cute ‘aloe ‘Heine MAXROWS deine MAXCOL4 main) i in“pis =| In") malloc (MAXROW size int"); Bills (int) mateo (MAKCOL* zee int)); } Q 5 How would youfteethememory allocated by te following program? frlude alert fete MAXROWS ‘tdetine MAXCOL 4 man) { ep bis ={int") mallee MAXROW* size int*)); Pj0]=( nt) maloc (MAXROW " MAXCOL” sot int) for(i=0j1. { ‘The following code s improper though it may work some times. How ints Seaolpoe et fee ae: ‘main() K { struct ox "p ert 00 Gerasrae at") nabs (a (st ex) ‘strcat (1, 82); -28 = ( char * ) malloc (20); print! ("Sbs", st) free (p); 1 1 Q in Q 1720 What would be the output ofthe second printf) in the following program? ‘ecu alos rin) ( int; (in) aloe ( 20); “To ree) we only pass the pointer tothe block of memory which we ‘want to deallocat, Then how does free) know how many bytes it should deallocate? Q 121 ‘What would be the output ofthe following program? pa eames Chapter 17: Memory Allocation 197 rude alos tt 7 ran) Q 1726 i inp; ‘What's te difference between malloc() and ealloc() functions? Int*) alos 20); Dain (6c, sieot(p)) 1127 troop); a ) Which function should be used to free the memory allocated by Q 122 calle) Q i728 ‘mailoc() allocates memory from the heap and not from the sick. Qiinss! ‘ Q i729 How mach maximum memory can we allocate ina singe call 10 Qos smalloc()? Q 1730 Suppose we ask realloc!) to increase the allocated space for a 2osinteger array to 2 40-integer array. Would it increase the acray space atthe same locaton at which the aray i present or would it VS SA STM gh try to find a different place forthe bigger array? Q zs Q 1725 (Can we dynamically allocate arrays in expanded memory? Whe allocating memory any thr poles poit nt hae pics af memary we hve to valu ese eer ples or Q 1732 ee eeteceeay Can 1 increase the sizeof a statically allocated array? yes, how? Point ou the error, ifany, in the following code. 198 Test Your C Skills ‘The output is unpredictable since bufers an auto aray and would dic when the control goes back to man). Thus s would be pointing ‘oan array which no longer exists. ate smain() her's char *fin(): s=fin(): pit ("6,8 } oat), state char but); stopy (buf, ‘RAM Rarely Adequate Maroy’); return (bur); ) Chapter 17: Memory Allocation 199 A m3 finde ‘aoc P=) char*s char" hi); s=fun(): rin ("5 8) free (2): “prs pir=(char*) lac): Stroy (pt, PAM- ray Adoqut Merry); return ( A 174 {include ‘alloc ‘tdfine MAX 10, rain) t*) malloc (MAK *sizeol(int) eMAK: +) past: pai (pa): i Faved estind Chapter 17: Memory Allocation 201 ea ras teat tenons ‘define MAXCOL 4 } ) Amz jn won -NANCO a); oss feo ‘Serenatcous fet: s); ay A is ‘e a. ee la og aie ac ee dae testo Focapieagalecieti OFAC anh Ae les get Pee tnle eyes A 16 'No, Since ptr is a uninitialised pointer it must be pointing et some ‘unknown location in memory. The string that we type in would get stored atthe location to which ptris pointing thereby overwriting ‘whatever is presenta that location. A 1720 ‘In most implementations of malloc() the number of bytes allocated is stored adjacent tothe allocated block, Hence itis simple ft eet) to know how many bytes to deallocate, Amz Aira t " 2 aster: Sedat A 2 ease sete ’ No A ms A ins a pre ere asec ised A m9 = Fe any amtc oiplnng as x eesvl “a Fake a omar pane i bape wee moesh Fe ts Ideally we should have used: Bs int") elle (0,40); it(ts=NULL) 206 ‘Test Your C Skis print | Cannot rellocats, leaves previous located ron unchangos" 7 the aay expanded athe sae region se free (p);* delcat th oral aay" /satpto nny allocated regen") ) A i724 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 forthe newly allocated space. Ai 1725 If realloct) expands allocated memory atthe same place then there iso need of readjustment of ther pointers. However, if allocates new region somewhere els the programmer has to readjust the other pointer. A 1726 ‘As against malloc(),calloe() needs two arguments, the number of elements to he allocated and the size ofeach element. For example, (int) ello (10, soo (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 O ‘Thus the above call to calloc is equivalent to: nt*)maloe (10° stot nt) }; ‘memset (p,0, 19° sizotint)); A 127 ‘The same that we use with mallac(), ie. freet), A 17.28 The A 1729 64KB. A 1730 Use the standard library functions farmalloc() and fafree(). These functions are specific 0 DOS, A 1731 ‘Yes. Using interrupt 0367, the details of which are beyond the Seope ofthis book 208 Test Your C Skills A is Chapter 18 ie aging ts re by malt we so pr Variable Number of Arguments Q ws Which header file should you include ifyouare to developa function which can accept variable numberof arguments? vararg.h siclibh sidio.s sdargh Q we ‘What would be the output ofthe following program? poEe nude ciioh> nude targ b> rain) fun (char 9, ..) ( {un | Noting spect 47.110); tt valstptr; 210 Test Your C Skis idee eee ay Ae ceo itr pint rm) 7 vata meg) rom=vaag( pt): rum=vacag (Bint): Es nt ("re urn); ' Q ws Isitmecessary than function which accepts variable argument ist, there should atleast be one fixed argument? Q 4s ‘Cam the fixed arguments passed to the function witch accepts vari- able argument ist oovur atthe end? Q ss Point out the ero, if any, inthe following program, indude rain() i vatun(3,7, 11,0}; , van (int, ..) 1 va stp int um ‘um = va_arg (tnt) Point out he erro, if any, in the folowing program, nude stdargho: man) 1 varun (3,75, 112,066): 1 vartn (in, .) fat"; let um; va stat (pn); rum = va_arg (py, int); print (enum Q wr Point out the errr, iPany, inthe following program, Froude stdaryn> rman) ( fun 1,4,7, 11,0); , fun(..) t 212 ‘Test Your C Skills vaistptr; enn va. stat (int): um = vag (int) print (6a, rum): ) Q ws ‘The macro va_staris used to iitialsea pointer othe beginning of the Iist of fixed arguments, Q 19 ‘The macro va_arg is use to extract an argument from the variable argument list and advance the pointer to the next argument Q 110 Point ou the error, if any, in the following program, Vinci seargh ‘main() { display (4a ) play otra.) i hare) va lstpr Chapter 18: Variable Number of Arguments 213 va_stan prem); forli=1 i enum; j++) vary pr char); pint ("ee ) Q wit “Mention any variable argument list funciton that you have used and its provorype. Q we Point ou the errr, ifany, inte following program. ncude “stag ‘main() delay (4,125,185, 145,443); ‘peach flat ints va lotpr: va sat pt rum). for(i ( enum; e+) = ¥a.ar (pr fost) pit "ural" 01: 214 (Chapier 18: Variable Number of Arguments 215 “a Q 15 (Can we wit function thats varsble argument ist and pases coe foes ncn (ich aes VG A sents) Point ot the ero in the fllowing program finde “tear Q 17 rani) ( Point out the error, if any. in the following program. splay (Hole 4.2126, 195,145,440) ' sue ‘soon mmain() deplay( char‘ nt umf, int rum...) ( { pay ("Ho 4 12,1916 44); float c; int; ’ va stp display (chars...) ‘va_stert (ptr, $) 5 t ‘c= va_arg ( ptr, double ); ‘show (8, ...) print! ("intel ®, ©); 1 ' ‘show (char “t,..) t Q wit ape ina; (Can we pas a atshle argument ist to a funtion at ransime? vasa); <¥esiNo> a= va_arg (pint); print ("S6, a)| Q 815 } Q@ 12s How would you rewrite program 18.17 such that show) 8 able 10 handle variable argument list? While defining a variable argument lst funetion can we drop the ellipsis...) Se aes Chapter 18: Variable Number of Arguments 217 a9 piste Q pe =tune, “Bye pipe): use the following pring to print a Zong int why Tam not warned thease ene bout the type mismatch? pint (5 num) rie) ipp10; Q 18.20 va lst va.sat( pt.) (Can you write function tha works sina to pring? eter te laieiie Cpt: Q 1821 p2= va_arg (int (*)()): Capes How can a called function determine the numberof arguments that b tavobeea pane to ah a Q 122 int (Heo); } CCan there be at least some solution to determine the number of a arguments pasted toa variable argument ist function? f nd): Q 1323 Point out the error in the following program. Q i824 se ow would you rtf the err in the program 18.23 above? int (p11); in (2)0: insuni(), una); Tess Your CSkity Chapter 18: Variable Number ofArguments _219. nis Answers A A 11 “hari fice argument the dfinton of fm a A iss A a2 Fase 4 A iss A iss Te Yes A 1810 A isa ‘While exacting acharargument ising arg we should havesed = asp i) Xo A wen A ws pit (co chara.) ‘Since pir has not been sef atthe beginning of the variable argument A 1812 list using va. start it may be pointing anywhere and hence a call 0 vi_arg would fetch a wrong inter. A 126 ‘While extracting float argument using va_arg we should have used = va_arg (pr, double). A 13.13 Irrespective ofthe type of argument passed to a function receiving Sener ans occa White setting the ptr tothe beginning of variable argument list we shawl have used va start (po, num? ) 220 ‘est Your C Skills A 181 No. Every actual argument list mustbe completely known atcompile time In that sensei snot tucly a variable argument list. A 815 Yes A 18.16 Yes A 1.17 ‘The call to show) is improper. Ths is not the way fo pass variable argument list toa funetion A 18.18 finlude "tdargh* rman) splay ("Holo 12,13, 14,44); ) isplay (chars, ..) vaistpr: va_stat (pt); ee) Chapter 18: Variable Number of Arguments 221 show (char vast tt) for(i=O;icajiee) ‘n= va_arg (prt nt) print (nen) 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 maich or must manually insert explicit typecass. A 1820 ude cea tery > mman\) ( 01d mpi (char): char* core (unsigned in int); inti 5 char sf] ="Ivanets ae hore to stay." 1 nt eng = i: void pint (char “nt, .) ( char'p: (Chapter 18: Variable Number of Arguments 223 case’! ini: s=ya.arg (gp har") aeiped puis(s); thas brea vast va. ag agp, ugned it); ‘va start ( arg, ft); ‘puts ( convert (, 10)) break; paint: for (path: "ple; pee) = va_arg (arg, unsigned it); ' puts ( convert (u, 16)); row) brosk; pputchar (*p) ; (puta (2) ; font; break; ) ) pa ) ase) va_end ( argp); case'c s 'a_argl argp int) ‘char * convert (unsigned! int um, it base | patch); i Deak: state char but); a, sharp tema au i) pir = abut (sizeof bufl)- 1] { ted ‘ ‘pusher ( puts cone 10)): broak; case aa = ag (fp, unsigned) peak us (convert (u, 8); bre; 224 Test Your C Skils (Chapter 18: Variable Number of Arguments 225 pe=hind; A 1821 depay( Bye" pl, 2); Ircannot. Any fonction that takes variable number of arguments asthe able to determine from the arguments herseves hove many play (cars .) of them there ae. The print) function, for example, dos this by { looking for format specitirs ed et.) inthe format sing. This is su "pp1 10, ("P9210: thereason why such fanctions fal badly ifthe format string does nt vaLketpt: smach the argument is. ‘ypodet nt tunep() vast (pi) : pt =va.arg( net). A ex Con: p= aang (pnt) When the arguments passed areal f same type we ean think of (m2 Ns sing a sentinel vale fike-1 or0 ora NULL pointer tthe end of ) the variable argument list Another way ould be to expiily pass the count of number of variable arguments nig Aes pr elo"); : ) vaarg cannot extat the function pointer fom the variable argu fina() tment Ist inthe manne tied here i prt (SH); } A 18.24 Use npedefas shown below: incu ‘stdarg ht ‘main() { Inept): Ine (p2): intuni(), una); Chapter 19 Complicated Declarations Q wi (What do the Following declarations signify? Cae ROROZEr ASH zOTmMOOEE im {05 ine “PAV char **argy void (10) ) inti); char far *r char far re 10] ine Saf5} inc far *p): char far *sert,*Scr2; ine tablel 1) void) = ( fad, fou, fal, fi} 5 int Spt 3015 int *pe(30) 5 void emp): void ("emp 0: ehar(* CUO har (* (XB) 151: void (#F Cin, void (3005 ine (Cine, nt ** (#) (int, int )) void (*£% void (* cin *, void **), int (* void *, int") 3 char far far "pt; char far * neat *pt char ft “huge *pe 28 ‘Test Your C Skills Q 192 ‘What would be the output ofthe following program? rman\) ( char near* nea‘; char near far “2 char near* hugs 3; Brin ("ed dc, sot (pt, sizeof (2) sizet(pt8)) Q ws ‘What would be the output of the following program? mmain() i charter“ near"pet; charter "far "2 charter" huge ‘a; rit ("dd snot prt), sieot (pt), zoo tra); Q 94 ‘What would be the output ofthe following program? rain) é char hugo * near ptt; char huge far “pt; char huge * huge‘ et ("Sd zat (pr) size |p), ie (ptr}); Chapler 19: Complicated Declarations ) Q ws What would be the ouput of the following program? main) ( ‘char huge * near far ptt char near “far * huge pt2; charfar "huge rin (7. 54 “pt; zat (pr). sect p2), seo (pra)); } Q 6 ‘What would be the output of the following program? * pear ta “pt chara "fer * huge ‘at charfar "huge near ‘pa rin (“ed 4%, sie (rt), seo “2, sie (“pra }); Q v7 What would be the ourput of the following program? rman) ( char huge *near® far ‘prt char near “ft huge 2 230 ‘Test Your C Skills charfor*huge* near ‘pt rit ("eda esol (pr) slzcl (“2 ste (8); Q we ‘What would be the output of the following program? mman() { chat huge *near* far“ char near far *huge 2 chatfar “huge “nea ‘pt pit "ede, izeot (p ),teo(pr2) sizot 3)} Q 29 ‘Ae the following two declarations same? car arf "sc char far arse Q 1910 ow would you declare the following: Anasryof tie pines 0 chars Anaray of te Chor pers At to an aay of ice cas 1 feier to fonction which eves and pointr and eens ‘pointer toa faction which recevies nothing and renurs leg Chapter 19: Complicated Declarations 231 Q wi Can you write a program which would implement the following declaration. vid ("int vod (*}) 5 Answer A 19.14. fis «function returning pointer to an i. A 19.18. fsa pointe o function which returns an int. A 19.16. args isa pointer toa char pointer A 1910. isan array of 10 function pointers, where each function reeivestwo ‘ngs and returns nothing, A 1918. cris far pointer a char. (far pointer sx pointer which contains an address which lies outside the data segment), 232 Test Your C Skills A iF. ‘arr an array of 10 far character pointers A 1916 ‘ais an array of 5 function pointers. Each ofthese functions receive 2 far pointer to an int and returns an in A 1918. serT is afar pointerto a char, whereas scr? sanear pointer to a char. A 1911 fable an ary offs pind wih po to the untions Fa), ou Jet. Eachfthexe anton accept nothing andretumn ‘nine A 1.14. pris a pointer to an aray of 30 integers A 191k. piris an aray of 30 pointers to integers A 1911. ‘mp is a function returing pointer to void. Chapter 19: Complicated Declarations 33 A 191M. ‘mp isa pointer to function which returns void A 191N. 4. fist ering poner 1 ary of poet acon A 1910. 1 is an aray of 3 pointers to functions returning pointer to “OFS hans ni A io.1P, ray fi8 8 pointer toa function which returns nothing and receives as is parameter an integer and a pointer to a function which receives pothing and returns nothin. A 1919 fis pointer to a funetion which returns a pointer to an int pointer and reeives two arguments a pointer foaninrpointer anda fnction pointer which points to a function which receives two pointers int pointers and retums a pointer to an ine pointer A 191R, {8a pointer to function which rewms nothing and receives (wo 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 a pointer toa void pointer; the second function pointer points toa function which returns an infpointerand receives a pointer to a void pointer and an int pointer. A 1918. iris «far pointer toa far pointer to char, or in easier words, ptr ‘onttins afar address ofa far pointer to a char A i917. or in easier words. ir “har era near pointer far pointer a char. ‘min aaron far ptr o A wiv. iris a huge pointe toa 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 196 444 A is9 No A 1910 char ‘o chart char (‘35 Moat pi }(nt*); wid (P() A 1911 main) fl 235 oi (in, aid (90) oun (in, vld(")0)) void an) void ("9)(); f P (*123,0) 1 voi un (int, void (°9)()) print (“Helo 1 i fut) C ) Chapter 20 Library Functions Q 21 What do the functions ato), i0a() and gevtt) 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 m3 How would you us gi into sr an iy of erste Q 24 How would you use gsor() function to sort the names stored in an uray of pointers to strings? 238 Q 25 How would you use bsearch) function fo search a name storedin an aay of pointers to strings? Q 26 How would you use the Funetons sin(), pow() grt)? Q 27 How would you use the function memepy()? Q »s How would you use the function memset()? Q »8 How would you use the function memmove()? Q 2.10 How would youuse the functions feekt, fread) firite()and fill)? Q mn How would you obtain he curent time and difference between tv9 times? Chapter 20: Library Functions 239 Q w2 How would you use the function randomize) and random)? Q 13 ‘Would the following program always output ‘Banglore"? ‘man() t chart] = “Bangor 440010"; chars simopy (st, si. 8) pri ("ns st). 1 Q wo ‘Can you shorten this code? rain) i charst] charst210) Banglore - 440010"; sjo)="0 ‘tinal (srs, 8] print ("68 2) 240 ‘Test Your CSkilly Q 215 How would you implement subst) function that extracts a substr- ing fram a given sting? Q 216 Given a sentence containing words separated by spaces how would you construct an array of pointer o strings conttining addresses of cach word in the sentence? Q 2.17 ‘Write the comparison function gs_compare(} forthe following code. struct date ( % ‘eompare (const void" cont void"); ined, y main) ( struct dala = (17,.11,62), (243, 78}, (17.11.82), {16, 12,78), (19, 2/84) ik : cts) Chapter 20: Library Funetions 24) zoo (set date) ‘sor (4,5, qs.compare) forli=Osie$;i) rind de LG, ey) Q 218 How should we sort linked fist? Q v0.19 ‘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 21 How would you printa string on the printer? Q 2022 ‘Can you use the function forint to display the output onthe screen? 242 est Your C Skills Answers A 201 stoi) Converts asring to an integer. ‘toa() Converts an integer toa string, sgevt() Conversa oating-point number toa string Firclude ‘tb ht rman() ( char sf] = "1245" cher butler5), sting) ins ates) print "nt. got (2.141672, 4, bur rit it’ but); oa (15, sng, 2}; eit (n,n) ) A 202 The function spriny)can be used for thispurpose. This function also has the ability to format the numbers as they are converted tostengs ‘The following program shows how to use this function, fino st ‘maint Chaprer 20: Library Functions Mat b =3.14 har sta}; sprint (st, puts (str) Hh A 23 ‘include "sting ht included ht siruct stud t intl; intmarts, ‘har nam) 1 int sor. (stct std stuct stu") int or nae (struct sta, stuct stud"); int or mari (stuct stud stuct stud"); mman|) ( stati stuct td ss {18,96 Akshay 2,87, "Macht) 8, 85,"Ashay 10,60, "Sushmta” i ) leer) Ws eizot stuct ud) print (rn order of rol numbers" ot (5,4, sortm) 244 Test Your C Skills for(x=0;x<4 244) Print (inks st, se rolno, sia} name, s]mars ) prt (rn order of nares"); for (4,1, sor name); for(x=0;x64 3x64) print (sid sc, se ono, sy name, sx] mars) pet (inn order of mas") sors, 4 w, sor ants) for(x=Osx<4 x4) a owe tio ote) int sor. (stuct std‘, sbust stud 2) i , retum (ttle 20} ison name (stuct tut, stuct sud 72) [ i int soars (struct sd, stuct std "2 { ) A 204 fnclude “tng include “i retum (stomp [t>name, name); rotun (2>marks-t->marts): in sot_name (cont vid, cone vid") Chapter 20: Library Functions 245 rain) ‘ char*names|]=( Aisha’ Macha “Nba Sushma, ~Sudeeiat i inti; vot (names, 6, szel (char), ot name) fer(i=0;1<5;4+) print (“ns namest) ) intsor_name (cont vid", canst voit] 1 and ae ways gontesto objects beng compared) char at cast appropily") t= (char™) te2=| char retum (stem (*t1,"122)) , A 25 fincuse “sting fecude “tbh int sor name corel void", const oid“) intbs_carpare char char") ‘man() ‘Test Your C Skills chartrames{]=( Aisha Macur’ Ava “sus, “suerte port (rames, §, sizeof chee) for(=0;1<5;ie) pi |weKs', names) ),sorname ): wide =sizet {names rel = sizeof (names ) wie: beseech (8, nares, nl wide, bs_corpare) it(b=NUL) ain "Not found") ose ie ts"); int sort name | const vidi, const ci 2) 11 anc are anaye pointers to objets bing compared“ hac™t, 22 Chapter 20: Library Funetions ‘etm (step ("t,122))5 ) int bs_compare (har "st, char""s2) i ‘otun (step (*st,"2)) ) A 206 ‘ncbte ‘matin rman) intang: float agra, x,y 20: print Enter he angle in degrees"): sant ("Bang angred = ang" 214/160; xesin( aogad); print incosine of angled i A 27 clude ‘mem ech ran) inten char sr] = "Pray, at or Egor la, bat for stonge back 8 Test Your C Stills aloe (area) rmemopy (dst, st, area). print (tse sc) Print 8" dst) ) A 208 facade mem’ main() i int ara char sre] = ‘Bon jour, Madam; aa = sito! (se); memset (st, 88-7); print (wis so) A 29 ‘include “mem include “alloc rmain() intaree char "det char rf] = Lie he camer and you aroha terol "go koep ering alvays" aa = seo! (sc) Chapter 20: Library Functions 249 est = mal area); memmove (des 8a); print et) pet (“8 s6) } A 20.0 neue ‘tort setsud { itl; cher na); fal per Je: rues: ‘aain( t eng pein =O. ivr hare fat temp; fe topen (sida): ‘puis ("Unable to open file"); ext(1) ’ o 250 Test Your C Skil (Chapter 20: Library Functions 251 Print (into code no. to mod"); ‘scar! ("%e' rlna); it =citine (2,11); hile (eas (Be, saat (2), 1,6) rit (“inrogram was active for second, i); if(o10lno = ono) [ print ("Enter the now rcor) A 22 Suan ("%s 2 ename,&temp ) nce “os ht ‘eper = temp nude ste he {eeak (poston, SEEK SET) ‘wit (Be, sizeof), 1,18); main) break; re ) randomize); postion = fl (15); Dal ("nPress any key to stop"); ) ile (abit )) [ ats "You want to moi recods"); ‘sound (random (500); ch = getchel ‘olay (random (100); ile (ch =") nosound) ' ) ) A 2011 #ncude "time A 2018 fncude “dos No, Because after copying the source string into the target sting rmain() sirnepy() doesnt terminate the target string with a "O'. A better way ( ‘of copying would be: tine 111.2 double dt, s129]=10 imi=2; stmcat sts, 8) time (at); strmcai() always terminates the target string with a "0" steep (i); time (82); { A 2014 char sti{] = "This is atest" ; fes, using springfi) as shown below: char’p. Ye ee uff) as shown belc ont a me a hrf} =p staat li ‘printf ( "Ses", st}; t 1 p=sirtok (NULL, ** cau A 20.15 es i =) F i pitl=p char stri[] = "Banglore’ aan r ian print ( "Ses", et); for{j=0;) sp2y, 254 Your C Skits retum (1); cof (=pt->m <mn) retu (-1] 5 lee (spt->m> sp2-om) retum (1) heel (=pt->d d) retum (-1); tse (sptnd> 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 Somting it ate. Sul if we want to sort the list then we can allocate a temporary aay of pointers, fit with pointers tothe various nodes. in thelist, call qsort() and finally rebuild thelist pointers based on the sorted aay A 20.19 rand! returns a random number random) returns arandom number ina specified rang. srand{)intilises a random number generator with a given seed, value. randomize) initilises 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 ‘memepy() is undefined whereas meme sorrectly. memépy() is more eff A 2021 incude “sd ht main() ( vel) caries out the copying cient, whereas memmove() is safer ‘har st = “There woud’ have been COBOL without * fin (sidpm, “ni etr); ) A 20.22 Yes, by replacing the usual file pointer with sidout as shown below. Iprint (tout, "ss ed tL);

You might also like