home *** CD-ROM | disk | FTP | other *** search
/ DP Tool Club 8 / CDASC08.ISO / VRAC / C0412.ZIP / C0412.TXT next >
Text File  |  1993-09-11  |  35KB  |  1,085 lines

  1.  
  2. Xref: nuchat comp.lang.c:76245 news.answers:12293
  3. Newsgroups: comp.lang.c,comp.answers,news.answers
  4. Path: nuchat!menudo.uh.edu!swrinde!gatech!howland.reston.ans.net!usc!cs.utexas.edu!uunet!nwnexus!oneworld!eskimo!scs
  5. From: scs@eskimo.com (Steve Summit)
  6. Subject: comp.lang.c Answers (Abridged) to Frequently Asked Questions (FAQ)
  7. Message-ID: <CD4LwH.5Bn@eskimo.com>
  8. Followup-To: poster
  9. Sender: scs@eskimo.com (Steve Summit)
  10. Supersedes: <CCny1x.My5@eskimo.com>
  11. Reply-To: scs@eskimo.com
  12. X-Archive-Name: C-faq/abridged
  13. Organization: none, at the moment
  14. Date: Fri, 10 Sep 1993 07:00:16 GMT
  15. X-Last-Modified: July 15, 1993
  16. Approved: news-answers-request@MIT.Edu
  17. Expires: Sun, 10 Oct 1993 00:00:00 GMT
  18. Lines: 1060
  19.  
  20. Archive-name: C-faq/abridged
  21. Comp-lang-c-archive-name: C-FAQ-list.abridged
  22.  
  23. [Last modified July 15, 1993 by scs.]
  24.  
  25. This article contains minimal answers to the comp.lang.c frequently-
  26. asked questions list.  Please see the long version (posted on the
  27. first of each month, or see question 17.22 for availability) for more
  28. detailed explanations and references.
  29.  
  30.  
  31. Section 1. Null Pointers
  32.  
  33. 1.1:    What is this infamous null pointer, anyway?
  34.  
  35. A:    For each pointer type, there is a special value -- the "null
  36. pointer" -- which is distinguishable from all other pointer
  37. values and which is not the address of any object.
  38.  
  39. 1.2:    How do I "get" a null pointer in my programs?
  40.  
  41. A:    A constant 0 in a pointer context is converted into a null
  42. pointer at compile time.  A "pointer context" is an
  43. initialization, assignment, or comparison with one side a
  44. variable or expression of pointer type, and (in ANSI standard C)
  45. a function argument which has a prototype in scope declaring a
  46. certain parameter as being of pointer type.  In other contexts
  47. (function arguments without prototypes, or in the variable part
  48. of variadic function calls) a constant 0 with an appropriate
  49. explicit cast is required.
  50.  
  51. 1.3:    What is NULL and how is it #defined?
  52.  
  53. A:    NULL is simply a preprocessor macro, #defined as 0 (or
  54. (void *)0), which is used (as a stylistic convention, in
  55. preference to unadorned 0's) to generate null pointers,
  56.  
  57. 1.4:    How should NULL be #defined on a machine which uses a nonzero
  58. bit pattern as the internal representation of a null pointer?
  59.  
  60. A:    The same as any other machine: as 0 (or (void *)0).  (The
  61. compiler makes the translation, upon seeing a 0, not the
  62. preprocessor.)
  63.  
  64. 1.5:    If NULL were defined as "(char *)0," wouldn't that make function
  65. calls which pass an uncast NULL work?
  66.  
  67. A:    Not in general.  The problem is that there are machines which
  68. use different internal representations for pointers to different
  69. types of data.  A cast is still required to tell the compiler
  70. which kind of null pointer is required, since it may be
  71. different from (char *)0.
  72.  
  73. 1.6:    I use the preprocessor macro "#define Nullptr(type) (type *)0"
  74. to help me build null pointers of the correct type.
  75.  
  76. A:    This trick, though valid, does not buy much.
  77.  
  78. 1.7:    Is the abbreviated pointer comparison "if(p)" to test for non-
  79. null pointers valid?  What if the internal representation for
  80. null pointers is nonzero?
  81.  
  82. A:    The construction "if(p)" works, regardless of the internal
  83. representation of null pointers, because the compiler
  84. essentially rewrites it as "if(p != 0)" and goes on to convert 0
  85. into the correct null pointer.
  86.  
  87. 1.8:    If "NULL" and "0" are equivalent, which should I use?
  88.  
  89. A:    Either; the distinction is entirely stylistic.
  90.  
  91. 1.9:    But wouldn't it be better to use NULL (rather than 0) in case
  92. the value of NULL changes, perhaps on a machine with nonzero
  93. null pointers?
  94.  
  95. A:    No.  NULL is, and will always be, 0.
  96.  
  97. 1.10:    I'm confused.  NULL is guaranteed to be 0, but the null pointer
  98. is not?
  99.  
  100. A:    A "null pointer" is a language concept whose particular internal
  101. value does not matter.  A null pointer is requested in source
  102. code with the character "0".  "NULL" is a preprocessor macro,
  103. which is always #defined as 0 (or (void *)0).
  104.  
  105. 1.11:    Why is there so much confusion surrounding null pointers?  Why
  106. do these questions come up so often?
  107.  
  108. A:    The fact that null pointers are represented both in source code,
  109. and internally to most machines, as zero invites unwarranted
  110. assumptions.  The use of a preprocessor macro (NULL) suggests
  111. that the value might change later, or on some weird machine.
  112.  
  113. 1.12:    I'm still confused.  I just can't understand all this null
  114. pointer stuff.
  115.  
  116. A:    A simple rule is, "Always use `0' or `NULL' for null pointers,
  117. and always cast them when they are used as arguments in function
  118. calls."
  119.  
  120. 1.13:    Given all the confusion surrounding null pointers, wouldn't it
  121. be easier simply to require them to be represented internally by
  122. zeroes?
  123.  
  124. A:    Such a requirement would accomplish little.
  125.  
  126. 1.14:    Seriously, have any actual machines really used nonzero null
  127. pointers?
  128.  
  129. A:    Machines manufactured by Prime, Honeywell-Bull, and CDC, as well
  130. as Symbolics Lisp Machines, have done so.
  131.  
  132. 1.15:    What does a run-time "null pointer assignment" error mean?
  133.  
  134. A:    It means that you've written through a null pointer.
  135.  
  136.  
  137. Section 2. Arrays and Pointers
  138.  
  139. 2.1:    I had the definition char a[6] in one source file, and in
  140. another I declared extern char *a.  Why didn't it work?
  141.  
  142. A:    The declaration extern char *a simply does not match the actual
  143. definition.  Use extern char a[].
  144.  
  145. 2.2:    But I heard that char a[] was identical to char *a.
  146.  
  147. A:    Not at all.  Arrays are not pointers.  A reference like x[3]
  148. generates different code depending on whether x is an array or a
  149. pointer.
  150.  
  151. 2.3:    So what is meant by the "equivalence of pointers and arrays"
  152. in C?
  153.  
  154. A:    An lvalue of type array-of-T which appears in an expression
  155. decays into a pointer to its first element; the type of the
  156. resultant pointer is pointer-to-T.  So for an array a and
  157. pointer p, you can say "p = a;" and then p[3] and a[3] will
  158. access the same element.
  159.  
  160. 2.4:    Why are array and pointer declarations interchangeable as
  161. function formal parameters?
  162.  
  163. A:    Since functions can never receive arrays as parameters, any
  164. parameter declarations which "look like" arrays are treated by
  165. the compiler as if they were pointers.
  166.  
  167. 2.5:    How can an array be an lvalue, if you can't assign to it?
  168.  
  169. A:    An array is not a "modifiable lvalue."
  170.  
  171. 2.6:    Why doesn't sizeof properly report the size of an array which is
  172. a parameter to a function?
  173.  
  174. A:    The sizeof operator reports the size of the pointer parameter
  175. which the function actually receives.
  176.  
  177. 2.7:    Someone explained to me that arrays were really just constant
  178. pointers.
  179.  
  180. A:    An array name is "constant" in that it cannot be assigned to,
  181. but an array is _not_ a pointer.
  182.  
  183. 2.8:    What is the real difference between arrays and pointers?
  184.  
  185. A:    Arrays automatically allocate space but are static; pointers are
  186. dynamic.
  187.  
  188. 2.9:    I came across some "joke" code containing the "expression"
  189. 5["abcdef"] .  How can this be legal C?
  190.  
  191. A:    Yes, array subscripting is commutative in C.  The array
  192. subscripting operation a[e] is defined as being equivalent to
  193. *((a)+(e)).
  194.  
  195. 2.10:    My compiler complained when I passed a two-dimensional array to
  196. a routine expecting a pointer to a pointer.
  197.  
  198. A:    The rule by which arrays decay into pointers is not applied
  199. recursively.  An array of arrays (i.e. a two-dimensional array
  200. in C) decays into a pointer to an array, not a pointer to a
  201. pointer.
  202.  
  203. 2.11:    How do I write functions which accept 2-dimensional arrays when
  204. the "width" is not known at compile time?
  205.  
  206. A:    It's not particularly easy.
  207.  
  208. 2.12:    How do I declare a pointer to an array?
  209.  
  210. A:    Usually, you don't want to.  Consider using a pointer to one of
  211. the array's elements instead.
  212.  
  213. 2.13:    How can I dynamically allocate a multidimensional array?
  214.  
  215. A:    It is usually best to allocate an array of pointers, and then
  216.  
  217. initialize each pointer to a dynamically-allocated "row."  See
  218. the full list for code samples.
  219.  
  220. 2.14:    How can I use statically- and dynamically-allocated
  221. multidimensional arrays interchangeably when passing them to
  222. functions?
  223.  
  224. A:    There is no single perfect method, but see the full list for
  225. some ideas.
  226.  
  227. 2.15:    Can I simulate a non-0-based array with a pointer?
  228.  
  229. A:    Not if the pointer points outside of the block of memory it is
  230. intended to access.
  231.  
  232. 2.16:    I passed a pointer to a function which initialized it, but the
  233. pointer in the caller was unchanged.
  234.  
  235. A:    The called function probably altered only the passed copy of the
  236. pointer.
  237.  
  238. 2.17:    I have a char * pointer that happens to point to some ints, and
  239. I want to step it over them.  Why doesn't "((int *)p)++;" work?
  240.  
  241. A:    In C, a cast operator is a conversion operator, and by
  242. definition it yields an rvalue, which cannot be assigned to, or
  243. incremented with ++.
  244.  
  245.  
  246. Section 3. Memory Allocation
  247.  
  248. 3.1:    Why doesn't the code "char *answer; gets(answer);" work?
  249.  
  250. A:    The pointer variable "answer" has not been set to point to any
  251. valid storage.  The simplest way to correct this fragment is to
  252. use a local array, instead of a pointer.
  253.  
  254. 3.2:    I can't get strcat to work.  I tried "char *s1 = "Hello, ",
  255. *s2 = "world!", *s3 = strcat(s1, s2);" but I got strange
  256. results.
  257.  
  258. A:    Again, the problem is that space for the concatenated result is
  259. not properly allocated.
  260.  
  261. 3.3:    But the man page for strcat says that it takes two char *'s as
  262. arguments.  How am I supposed to know to allocate things?
  263.  
  264. A:    In general, when using pointers you _always_ have to consider
  265. memory allocation, at least to make sure that the compiler is
  266. doing it for you.
  267.  
  268. 3.4:    I have a function that is supposed to return a string, but when
  269. it returns to its caller, the returned string is garbage.
  270.  
  271. A:    Make sure that the memory to which the function returns a
  272. pointer is correctly (i.e. not locally) allocated.
  273.  
  274. 3.5:    You can't use dynamically-allocated memory after you free it,
  275. can you?
  276.  
  277. A:    No.  Some early man pages implied otherwise, but the claim is no
  278. longer valid.
  279.  
  280. 3.6:    How does free() know how many bytes to free?
  281.  
  282. A:    The malloc/free package remembers the size of each block it
  283. allocates and returns.
  284.  
  285. 3.7:    So can I query the malloc package to find out how big an
  286. allocated block is?
  287.  
  288. A:    Not portably.
  289.  
  290. 3.8:    When I free a dynamically-allocated structure containing
  291. pointers, do I have to free each subsidiary pointer first?
  292.  
  293. A:    Yes.
  294.  
  295. 3.9:    Why doesn't my program's memory usage go down when I free
  296. memory?
  297.  
  298. A:    Most implementations of malloc/free do not return freed memory
  299. to the operating system.
  300.  
  301. 3.10:    Is it legal to pass a null pointer as the first argument to
  302. realloc()?
  303.  
  304. A:    ANSI C sanctions this usage, but several earlier implementations
  305. do not support it.
  306.  
  307. 3.11:    Is it safe to use calloc's zero-fill guarantee for pointer and
  308. floating-point values?
  309.  
  310. A:    No.
  311.  
  312. 3.12:    What is alloca and why is its use discouraged?
  313.  
  314. A:    alloca allocates memory which is automatically freed when the
  315. function which called alloca returns.  alloca cannot be written
  316. portably, is difficult to implement on machines without a stack,
  317. and fails under certain conditions if implemented simply.
  318.  
  319.  
  320. Section 4. Expressions
  321.  
  322. 4.1:    Why doesn't the code "a[i] = i++;" work?
  323.  
  324. A:    The variable i is both referenced and modified in the same
  325. expression.
  326.  
  327. 4.2:    Under my compiler, the code "int i = 7; printf("%d\n", i++ * i++);"
  328. prints 49.  Regardless of the order of evaluation, shouldn't it
  329. print 56?
  330.  
  331. A:    The operations implied by the postincrement and postdecrement
  332. operators ++ and -- are performed at some time after the
  333. operand's former values are yielded and before the end of the
  334. expression, but not necessarily immediately after, or before
  335. other parts of the expression are evaluated.
  336.  
  337. 4.3:    But what about the &&, ||, and comma operators?
  338.  
  339. A:    There is a special exception for those operators, (as well
  340. as ?: ); left-to-right evaluation is guaranteed.
  341.  
  342. 4.4:    If I'm not using the value of the expression, should I use i++
  343. or ++i to increment a variable?
  344.  
  345. A:    Since the two forms differ only in the value yielded, they are
  346. entirely equivalent when only their side effect is needed.
  347.  
  348. 4.5:    Why doesn't the code "int a = 1000, b = 1000;
  349. long int c = a * b;" work?
  350.  
  351. A:    You must manually cast one of the operands to (long).
  352.  
  353.  
  354. Section 5. ANSI C
  355.  
  356. 5.1:    What is the "ANSI C Standard?"
  357.  
  358. A:    In 1983, the American National Standards Institute commissioned
  359. a committee, X3J11, to standardize the C language.  After a
  360. long, arduous process, the committee's work was finally ratified
  361. as an American National Standard, X3.159-1989, on December 14,
  362. 1989, and published in the spring of 1990.  The Standard has
  363. also been adopted as ISO/IEC 9899:1990.
  364.  
  365. 5.2:    How can I get a copy of the Standard?
  366.  
  367. A:    ANSI X3.159 has been officially superseded by ISO 9899.  Copies
  368. are available from the American National Standards Institute in
  369. New York, or from Global Engineering Documents in Irvine, CA.
  370. See the unabridged list for addresses.
  371.  
  372. 5.3:    Does anyone have a tool for converting old-style C programs to
  373. ANSI C, or for automatically generating prototypes?
  374.  
  375. A:    See the full list for details.
  376.  
  377. 5.4:    How do I keep the ANSI "stringizing" preprocessing operator from
  378. stringizing the macro's name rather than its value?
  379.  
  380. A:    You must use a two-step #definition to force the macro to be
  381. expanded as well as stringized.
  382.  
  383. 5.5:    What's the difference between "char const *p" and
  384. "char * const p"?
  385.  
  386. A:    The former is a pointer to a constant character; the latter is a
  387. constant pointer to a character.
  388.  
  389. 5.6:    Why can't I pass a char ** to a function which expects a
  390. const char **?
  391.  
  392. A:    The rule which permits slight mismatches in qualified pointer
  393. assignments is not applied recursively.
  394.  
  395. 5.7:    My ANSI compiler complains about a mismatch when it sees
  396.  
  397. extern int func(float);
  398.  
  399. int func(x)
  400. float x;
  401. {...
  402.  
  403. A:    You have mixed the new-style prototype declaration
  404. "extern int func(float);" with the old-style definition
  405. "int func(x) float x;".  "Narrow" types are treated differently
  406. according to which syntax is used.  The problem can be fixed by
  407. using either new-style (prototype) or old-style syntax
  408. consistently.
  409.  
  410. 5.8:    Why does the declaration "extern f(struct x {int s;} *p);" give
  411. me a warning message?
  412.  
  413. A:    A struct declared only within a prototype cannot be compatible
  414. with other structs declared in the same source file.
  415.  
  416. 5.9:    I'm getting strange syntax errors inside code which I've
  417. #ifdeffed out.
  418.  
  419. A:    Under ANSI C, #ifdeffed-out text must still consist of "valid
  420. preprocessing tokens."  This means that there must be no
  421. unterminated comments or quotes (i.e. no single apostrophes),
  422. and no newlines inside quotes.
  423.  
  424. 5.10:    Can I declare main as void, to shut off these annoying "main
  425. returns no value" messages?
  426.  
  427. A:    No.
  428.  
  429. 5.11:    Is exit(status) truly equivalent to returning status from main?
  430.  
  431. A:    Yes.
  432.  
  433. 5.12:    Why does the ANSI Standard not guarantee more than six monocase
  434. characters of external identifier significance?
  435.  
  436. A:    The problem is older linkers which cannot be forced (by mere
  437. words in a Standard) to upgrade.
  438.  
  439. 5.13:    What is the difference between memcpy and memmove?
  440.  
  441. A:    memmove offers guaranteed behavior if the source and destination
  442. arguments overlap.
  443.  
  444. 5.14:    My compiler is rejecting the simplest possible test programs,
  445. with all kinds of syntax errors.
  446.  
  447. A:    Perhaps it is a pre-ANSI compiler.
  448.  
  449. 5.15:    Why won't frobozz-cc, which claims to be ANSI compliant, accept
  450. this code?
  451.  
  452. A:    Are you sure that the code being rejected doesn't rely on some
  453. non-Standard extension?
  454.  
  455. 5.16:    Is char a[3] = "abc"; legal?
  456.  
  457. A:    Yes.
  458.  
  459. 5.17:    What are #pragmas and what are they good for?
  460.  
  461.  
  462. A:    The #pragma directive provides a single, well-defined "escape
  463. hatch" which can be used for extensions.
  464.  
  465.  
  466. Section 6. C Preprocessor
  467.  
  468. 6.1:    How can I write a generic macro to swap two values?
  469.  
  470. A:    There is no good answer to this question.  The best all-around
  471. solution is probably to forget about using a macro.
  472.  
  473. 6.2:    I have some old code that tries to construct identifiers with a
  474. macro like "#define Paste(a, b) a/**/b ", but it doesn't work
  475. any more.
  476.  
  477. A:    Try the ANSI token-pasting operator ##.
  478.  
  479. 6.3:    What's the best way to write a multi-statement cpp macro?
  480.  
  481. A:    #define Func() do {stmt1; stmt2; ... } while(0)  /* (no trailing ;) */
  482.  
  483. 6.4:    Is it acceptable for one header file to #include another?
  484.  
  485. A:    There has been considerable debate surrounding this question.
  486.  
  487. 6.5:    Does the sizeof operator work in preprocessor #if directives?
  488.  
  489. A:    No.
  490.  
  491. 6.6:    How can I use a preprocessor #if expression to detect
  492. endianness?
  493.  
  494. A:    You probably can't.
  495.  
  496. 6.7:    I've got this tricky processing I want to do at compile time and
  497. I can't figure out a way to get cpp to do it.
  498.  
  499. A:    Consider writing your own little special-purpose preprocessing
  500. tool, instead.
  501.  
  502. 6.8:    How can I preprocess some code to remove selected conditional
  503. compilations, without preprocessing everything?
  504.  
  505. A:    Look for a program called unifdef.
  506.  
  507. 6.9:    How can I list all of the pre#defined identifiers?
  508.  
  509. A:    Try extracting printable strings from the compiler or
  510. preprocessor executable.
  511.  
  512. 6.10:    How can I write a cpp macro which takes a variable number of
  513. arguments?
  514.  
  515. A:    Here is one popular trick.  Note that the parentheses around
  516. printf's argument list are in the macro call, not the
  517. definition.
  518.  
  519. #define DEBUG(args) (printf("DEBUG: "), printf args)
  520.  
  521. if(n != 0) DEBUG(("n is %d\n", n));
  522.  
  523.  
  524. Section 7. Variable-Length Argument Lists
  525.  
  526. 7.1:    How can I write a function that takes a variable number of
  527. arguments?
  528.  
  529. A:    Use the <stdarg.h> (or older <varargs.h>) header.
  530.  
  531. 7.2:    How can I write a function that takes a format string and a
  532. variable number of arguments, like printf, and passes them to
  533. printf to do most of the work?
  534.  
  535. A:    Use vprintf, vfprintf, or vsprintf.
  536.  
  537. 7.3:    How can I discover how many arguments a function was actually
  538. called with?
  539.  
  540. A:    Any function which takes a variable number of arguments must be
  541. able to determine from the arguments themselves how many of them
  542. there are.
  543.  
  544. 7.4:    I can't get the va_arg macro to pull in an argument of type
  545. pointer-to-function.
  546.  
  547. A:    Use a typedef.
  548.  
  549. 7.5:    How can I write a function which takes a variable number of
  550. arguments and passes them to some other function (which takes a
  551. variable number of arguments)?
  552.  
  553. A:    In general, you cannot.
  554.  
  555. 7.6:    How can I call a function with an argument list built up at run
  556. time?
  557.  
  558. A:    You can't.
  559.  
  560.  
  561. Section 8. Boolean Expressions and Variables
  562.  
  563. 8.1:    What is the right type to use for boolean values in C?  Why
  564. isn't it a standard type?  Should #defines or enums be used for
  565. the true and false values?
  566.  
  567. A:    C does not provide a standard boolean type, because picking one
  568. involves a space/time tradeoff which is best decided by the
  569. programmer.  The choice between #defines and enums is arbitrary
  570. and not terribly interesting.
  571.  
  572. 8.2:    What if a built-in boolean or relational operator "returns"
  573. something other than 1?
  574.  
  575. A:    When a boolean value is generated by a built-in operator, it is
  576. guaranteed to be 1 or 0.  (This is _not_ true for some library
  577. routines such as isalpha.)
  578.  
  579.  
  580. Section 9. Structs, Enums, and Unions
  581.  
  582. 9.1:    What is the difference between an enum and a series of
  583. preprocessor #defines?
  584.  
  585. A:    At the present time, there is little difference.  The ANSI
  586. standard states that enumerations are compatible with integral
  587. types.
  588.  
  589. 9.2:    I heard that structures could be assigned to variables and
  590. passed to and from functions, but K&R I says not.
  591.  
  592. A:    These operations are supported by all modern compilers.
  593.  
  594. 9.3:    How does struct passing and returning work?
  595.  
  596. A:    If you really need to know, see the unabridged list.
  597.  
  598. 9.4:    I have a program which works correctly, but dumps core after it
  599. finishes.  Why?
  600.  
  601. A:    Check to see if a structure type declaration just before main is
  602. missing its trailing semicolon, causing the compiler to believe
  603. that main returns a structure.  See also question 17.15.
  604.  
  605. 9.5:    Why can't you compare structs?
  606.  
  607. A:    There is no reasonable way for a compiler to implement struct
  608. comparison which is consistent with C's low-level flavor.
  609.  
  610. 9.6:    I came across some code that declared a structure with the last
  611. member an array of one element, and then did some tricky
  612. allocation to make the array act like it had several elements.
  613. Is this legal and/or portable?
  614.  
  615. A:    The ANSI C standard allows it, but only implicitly.
  616.  
  617. 9.7:    How can I determine the byte offset of a field within a
  618. structure?
  619.  
  620. A:    ANSI C defines the offsetof macro, which should be used if
  621. available.
  622.  
  623. 9.8:    How can I access structure fields by name at run time?
  624.  
  625. A:    Build a table of names and offsets, using the offsetof() macro.
  626.  
  627. 9.9:    Why does sizeof report a larger size than I expect for a
  628. structure type, as if there was padding at the end?
  629.  
  630. A:    The alignment of arrays of structures must be preserved.
  631.  
  632. 9.10:    Can I turn off structure padding?
  633.  
  634. A:    There is no standard method.
  635.  
  636. 9.11:    Can I initialize unions?
  637.  
  638. A:    ANSI Standard C allows an initializer for the first member.
  639.  
  640.  
  641. Section 10. Declarations
  642.  
  643. 10.1:    How do you decide which integer type to use?
  644.  
  645. A:    If you might need large values, use long.  Otherwise, if space
  646. is very important, use short.  Otherwise, use int.
  647.  
  648. 10.2:    What should the 64-bit type on new, 64-bit machines be?
  649.  
  650. A:    There are arguments in favor of both long int and long long int.
  651.  
  652. 10.3:    I can't seem to define a linked list node which contains a
  653. pointer to itself.
  654.  
  655. A:    Structs in C can certainly contain pointers to themselves; the
  656. discussion and example in section 6.5 of K&R make this clear.
  657. Problems arise if an attempt is made to define (and use) a
  658. typedef in the midst of such a declaration; avoid this.
  659.  
  660. 10.4:    How do I declare an array of pointers to functions returning
  661. pointers to functions returning pointers to characters?
  662.  
  663. A:    char *(*(*a[5])())();
  664. Using a chain of typedefs, or the cdecl program, makes these
  665. declarations easier.
  666.  
  667. 10.5:    How can I declare a function that returns a pointer to a
  668. function of its own type?
  669.  
  670. A:    You can't do it directly.
  671.  
  672. 10.6:    What's the best way to declare and define global variables?
  673.  
  674. A:    It is best to place the definition in some central .c file, with
  675. an external declaration in a header file.
  676.  
  677. 10.7:    How do I initialize a pointer to a function?
  678.  
  679. A:    Use something like "extern int func(); int (*fp)() = func;" .
  680.  
  681. 10.8:    I've seen different methods used for calling through pointers to
  682. functions.
  683.  
  684. A:    The extra parentheses and explicit * are now officially
  685. optional, although some older implementations require them.
  686.  
  687.  
  688. Section 11. Stdio
  689.  
  690. 11.1:    Why doesn't the code "char c; while((c = getchar()) != EOF)..."
  691. work?
  692.  
  693. A:    The variable to hold getchar's return value must be an int.
  694.  
  695. 11.2:    Why doesn't the code scanf("%d", i); work?
  696.  
  697. A:    You must always pass addresses to scanf.
  698.  
  699. 11.3:    Why doesn't the code double d; scanf("%f", &d); work?
  700.  
  701. A:    With scanf, use %lf for double, and %f for float.
  702.  
  703. 11.4:    Why won't the code "while(!feof(fp)) fgets(buf, MAXLINE, fp);"
  704. work?
  705.  
  706. A:    EOF is only indicated _after_ an input routine has reached
  707. end-of-file.
  708.  
  709. 11.5:    Why does everyone say not to use gets()?
  710.  
  711. A:    It cannot be prevented from overflowing the input buffer.
  712.  
  713. 11.6:    Why does errno contain ENOTTY after a call to printf?
  714.  
  715. A:    Don't worry about it.  It is only meaningful for a program to
  716. inspect the contents of errno after an error has occurred.
  717.  
  718. 11.7:    My program's prompts and intermediate output don't always show
  719.  
  720. up on the screen, especially when I pipe the output through
  721. another program.
  722.  
  723. A:    It is best to use an explicit fflush(stdout) whenever output
  724. should definitely be visible.
  725.  
  726. 11.8:    When I read from the keyboard with scanf, it seems to hang until
  727. I type one extra line of input.
  728.  
  729. A:    scanf was designed for free-format input, which is seldom what
  730. you want when reading from the keyboard.
  731.  
  732. 11.9:    I'm trying to update a file in place, by using fopen mode "r+",
  733. but it's not working.
  734.  
  735. A:    Be sure to call fseek between reading and writing.
  736.  
  737. 11.10:    How can I read one character at a time, without waiting for the
  738. RETURN key?
  739.  
  740. A:    See question 16.1.
  741.  
  742. 11.11:    Will fflush(stdin) flush unread characters from the standard
  743. input stream?
  744.  
  745. A:    No.
  746.  
  747. 11.12:    How can I redirect stdin or stdout from within a program?
  748.  
  749. A:    Use freopen.
  750.  
  751. 11.13:    Once I've used freopen, how can I get the original stdout back?
  752.  
  753. A:    It's not easy.  Try avoiding freopen.
  754.  
  755. 11.14:    How can I recover the file name given an open file descriptor?
  756.  
  757. A:    This problem is, in general, insoluble.  It is best to remember
  758. the names of files yourself when you open them.
  759.  
  760.  
  761. Section 12. Library Subroutines
  762.  
  763. 12.1:    Why does strncpy not always write a '\0'?
  764.  
  765. A:    For mildly-interesting historical reasons.
  766.  
  767. 12.2:    I'm trying to sort an array of strings with qsort, using strcmp
  768. as the comparison function, but it's not working.
  769.  
  770. A:    You'll have to write a "helper" comparison function which takes
  771. two generic pointer arguments, converts them to char **, and
  772. dereferences them, yielding char *'s which can be usefully
  773. compared.
  774.  
  775. 12.3:    Now I'm trying to sort an array of structures with qsort.  My
  776. comparison routine takes pointers to structures, but the
  777. compiler complains that the function is of the wrong type for
  778. qsort.  How can I cast the function pointer to shut off the
  779. warning?
  780.  
  781. A:    The conversions must be in the comparison function, which must
  782. be declared as accepting "generic pointers" (const void * or
  783. char *).
  784.  
  785. 12.4:    How can I convert numbers to strings?
  786.  
  787. A:    Just use sprintf.
  788.  
  789. 12.5:    How can I get the time of day in a C program?
  790.  
  791. A:    Just use the time, ctime, and/or localtime functions.
  792.  
  793. 12.6:    How can I convert a struct tm or a string into a time_t?
  794.  
  795. A:    The ANSI mktime routine converts a struct tm to a time_t.
  796. No standard routine exists to parse strings.
  797.  
  798. 12.7:    I need a random number generator.
  799.  
  800. A:    The standard C library has one: rand().
  801.  
  802. 12.8:    Each time I run my program, I get the same sequence of numbers
  803. back from rand().
  804.  
  805. A:    You can call srand() to seed the pseudo-random number generator
  806. with a more random initial value.
  807.  
  808. 12.9:    I need a random true/false value, so I'm taking rand() % 2, but
  809. it's just alternating 0, 1, 0, 1, 0...
  810.  
  811. A:    Try using the higher-order bits.
  812.  
  813. 12.10-14:I 'm trying to port this old program.  Why do I get "undefined
  814. external" errors for some library routines?
  815.  
  816. A:    Some semistandard routines have been renamed or replaced over
  817. the years; see the full list for details.
  818.  
  819. 12.15:    How can I execute a command with system() and read its output
  820. into a program?
  821.  
  822. A:    Unix and some other systems provide a popen() routine.
  823.  
  824. 12.16:    How can I read a directory in a C program?
  825.  
  826. A:    See if you can use the opendir() and readdir() routines.
  827.  
  828.  
  829. Section 13. Lint
  830.  
  831. 13.1:    I just typed in this program, and it's acting strangely.
  832. Can you see anything wrong with it?
  833.  
  834. A:    Try running lint first.
  835.  
  836. 13.2:    How can I shut off the "warning: possible pointer alignment
  837. problem" message lint gives me for each call to malloc?
  838.  
  839. A:    It may be easier simply to ignore the message, perhaps in an
  840. automated way with grep -v.
  841.  
  842. 13.3:    Where can I get an ANSI-compatible lint?
  843.  
  844. A:    See the unabridged list for two commercial products.
  845.  
  846.  
  847. Section 14. Style
  848.  
  849. 14.1:    Is the code "if(!strcmp(s1, s2))" good style?
  850.  
  851. A:    Not particularly.
  852.  
  853. 14.2:    What's the best style for code layout in C?
  854.  
  855. A:    There is no one "best style," but see the full list for a few
  856. suggestions.
  857.  
  858. 14.3:    Where can I get the "Indian Hill Style Guide" and other coding
  859. standards?
  860.  
  861. A:    See the unabridged list.
  862.  
  863.  
  864. Section 15. Floating Point
  865.  
  866. 15.1:    My floating-point calculations are acting strangely and giving
  867. me different answers on different machines.
  868.  
  869. A:    First, make sure that you have #included <math.h>, and correctly
  870. declared other functions returning double.  If the problem isn't
  871. that simple, see the full list for a brief explanation, or any
  872. good programming book for a better one.
  873.  
  874. 15.2:    I keep getting "undefined: _sin" compilation errors.
  875.  
  876. A:    Make sure you're linking against the correct math library.
  877.  
  878. 15.3:    Why doesn't C have an exponentiation operator?
  879.  
  880. A:    Try using the pow() function.
  881.  
  882. 15.4:    I'm having trouble with a Turbo C program which crashes and says
  883. something like "floating point formats not linked."
  884.  
  885. A:    Some compilers for small machines, including Turbo C, attempt to
  886. leave out floating point support if it looks like it will not be
  887. needed.  The programmer must occasionally insert an extra,
  888. explicit call to a floating-point library routine to force
  889. loading of floating-point support.
  890.  
  891.  
  892. Section 16. System Dependencies
  893.  
  894. 16.1:    How can I read a single character from the keyboard without
  895. waiting for a newline?
  896.  
  897. A:    Contrary to popular belief and many people's wishes, this is not
  898. a C-related question.  How to do so is a function of the
  899. operating system in use.
  900.  
  901. 16.2:    How can I find out if there are characters available for reading
  902. (and if so, how many)?  Alternatively, how can I do a read that
  903. will not block if there are no characters available?
  904.  
  905. A:    These, too, are entirely operating-system-specific.
  906.  
  907. 16.3:    How can I clear the screen?
  908.  
  909. A:    Such things depend on the output device you're using.
  910.  
  911. 16.4:    How do I read the mouse?
  912.  
  913. A:    What system are you using?
  914.  
  915. 16.5:    How can my program discover the complete pathname to the
  916. executable file from which it was invoked?
  917.  
  918. A:    argv[0] may contain all or part of the pathname.  You may be
  919. able to duplicate the command language interpreter's search path
  920. logic to locate the executable.
  921.  
  922. 16.6:    How can a process change an environment variable in its caller?
  923.  
  924. A:    In general, it cannot.
  925.  
  926. 16.7:    How can I find out the size of a file, prior to reading it in?
  927.  
  928. A:    You might be able to get an estimate using stat() or
  929. fseek/ftell.
  930.  
  931. 16.8:    How can a file be shortened in-place without completely clearing
  932. or rewriting it?
  933.  
  934. A:    There are various ways to do this, but there is no truly
  935. portable solution.
  936.  
  937. 16.9:    How can I implement a delay, or time a user's response, with
  938. sub-second resolution?
  939.  
  940. A:    Unfortunately, there is no portable way.
  941.  
  942. 16.10:    How can I read in an object file and jump to routines in it?
  943.  
  944. A:    You want a dynamic linker and/or loader.
  945.  
  946.  
  947. Section 17. Miscellaneous
  948.  
  949. 17.1:    What can I safely assume about the initial values of variables
  950. which are not explicitly initialized?
  951.  
  952. A:    Variables with "static" duration start out as 0, as if the
  953. programmer had initialized them.  Variables with "automatic"
  954. duration, and dynamically-allocated memory, start out containing
  955. garbage (with the exception of calloc).
  956.  
  957. 17.2:    How can I write data files which can be read on other machines
  958. with different data formats?
  959.  
  960. A:    The best solution is to use text files.
  961.  
  962. 17.3:    How can I return several values from a function?
  963.  
  964. A:    Either pass pointers to locations which the function can fill
  965. in, or have the function return a structure containing the
  966. desired values.
  967.  
  968. 17.4:    How can I call a function, given its name as a string?
  969.  
  970. A:    The most straightforward thing to do is maintain a
  971. correspondence table of names and function pointers.
  972.  
  973. 17.5:    I seem to be missing the system header file <sgtty.h>.
  974. Can someone send me a copy?
  975.  
  976. A:    You cannot just pick up a copy of someone else's header file and
  977.  
  978. expect it to work, since the definitions within header files are
  979. frequently system-dependent.  Contact your vendor.
  980.  
  981. 17.6:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  982. from C?
  983.  
  984. A:    The answer is entirely dependent on the machine and the specific
  985. calling sequences of the various compilers in use.
  986.  
  987. 17.7:    Does anyone know of a program for converting Pascal or FORTRAN
  988. to C?
  989.  
  990. A:    Several public-domain programs are available, namely ptoc, p2c,
  991. and f2c.  See the full list for details.
  992.  
  993. 17.8:    Where can I get copies of all these public-domain programs?
  994.  
  995. A:    See the regular postings in the comp.sources.unix and
  996. comp.sources.misc newsgroups for information.
  997.  
  998. 17.9:    When will the next Obfuscated C Code Contest be held?  
  999. How can I get a copy of the previous winning entries?
  1000.  
  1001. A:    See the full list, or send e-mail to judges@toad.com .
  1002.  
  1003. 17.10:    Why don't C comments nest?  Are they legal inside quoted
  1004. strings?
  1005.  
  1006. A:    Nested comments would cause more harm than good.  The character
  1007. sequences /* and */ are not special within double-quoted
  1008. strings.
  1009.  
  1010. 17.11:    How can I implement sets and/or arrays of bits?
  1011.  
  1012. A:    Use arrays of char or int, with a few macros to access the right
  1013. bit at the right index.
  1014.  
  1015. 17.12:    What is the most efficient way to count the number of bits which
  1016. are set in a value?
  1017.  
  1018. A:    This and many other similar bit-twiddling problems can often be
  1019. sped up and streamlined using lookup tables.
  1020.  
  1021. 17.13:    How can I make this code more efficient?
  1022.  
  1023. A:    Efficiency is not important nearly as often as people tend to
  1024. think it is.  Most of the time, by simply paying attention to
  1025. good algorithm choices, perfectly acceptable results can be
  1026. achieved.
  1027.  
  1028. 17.14:    Are pointers really faster than arrays?  How much do function
  1029. calls slow things down?
  1030.  
  1031. A:    Precise answers to these and many similar questions depend of
  1032. course on the processor and compiler in use.
  1033.  
  1034. 17.15:    This program crashes before it even runs!
  1035.  
  1036. A:    Look for very large, local arrays.
  1037. (See also question 9.4.)
  1038.  
  1039. 17.16:    What does "Segmentation violation" mean?
  1040.  
  1041. A:    It generally means that your program tried to access memory it
  1042. shouldn't have.
  1043.  
  1044. 17.17:    My program is crashing, apparently somewhere down inside malloc.
  1045.  
  1046. A:    Make sure you aren't using more memory than you malloc'ed,
  1047. especially for strings (which need strlen() + 1 bytes).
  1048.  
  1049. 17.18:    Does anyone have a C compiler test suite I can use?
  1050.  
  1051. A:    See the full list for several sources.
  1052.  
  1053. 17.19:    Where can I get a YACC grammar for C?
  1054.  
  1055. A:    See the ANSI Standard, or the unabridged list.
  1056.  
  1057. 17.20:    How do you pronounce "char"?
  1058.  
  1059. A:    Like the English words "char," "care," or "car" (your choice).
  1060.  
  1061. 17.21:    What's a good book for learning C?
  1062.  
  1063. A:    There are far too many to list here; the full list contains a
  1064. few pointers.
  1065.  
  1066. 17.22:    Where can I get extra copies of this list?
  1067.  
  1068. A:    For now, just pull it off the net; the unabridged version is
  1069. normally posted on the first of each month, with an Expiration:
  1070. line which should keep it around all month.  It can also be
  1071. found in the newsgroups comp.answers and news.answers .  Several
  1072. sites archive news.answers postings and other FAQ lists,
  1073. including this one: two sites are rtfm.mit.edu (directory
  1074. pub/usenet), and ftp.uu.net (directory usenet).  The archie
  1075. server should help you find others.
  1076.  
  1077.  
  1078. Steve Summit
  1079. scs@eskimo.com
  1080.  
  1081. This article is Copyright 1988, 1990-1993 by Steve Summit.
  1082. It may be freely redistributed so long as the author's name, and this
  1083. notice, are retained.
  1084.  
  1085.