home *** CD-ROM | disk | FTP | other *** search
/ Danny Amor's Online Library / Danny Amor's Online Library - Volume 1.iso / html / faqs / faq / c-faq / abridged next >
Encoding:
Text File  |  1995-07-25  |  38.5 KB  |  1,263 lines

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