Sie sind auf Seite 1von 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

Das könnte Ihnen auch gefallen