Document Actions

Share or Embed Document

FREQUENTLY ASKED QUESTIONS IN C LANGUAGE

Section 1. Declarations and Initializations: 1.How do you decide which integer type to use? ans.If you might need large values (tens of thousands), Otherwise,if space is very important,use short.Otherwise,use int. 2: What should the 64-bit type on new, 64-bit machines be? ans. There are arguments in favor of long int and long long int, options. 3. What's the best way to declare and define global variables? ans. The best arrangement is to place each definition in some file, with an external declaration in a header file. use long.

among other

relevant .c

4.I can't seem to define a linked list node which contains a pointer to itself. ans. Structures in C can certainly contain pointers to themselves; the discussion and example in section 6.5 of K&R make this clear. Problems arise if an attempt is made to define (and use) a typedef in the midst of such a declaration; avoid this. 5. How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters? ans. char *(*(*a[N])())(); Using a chain of typedefs, or the cdecl program, makes these declarations easier.: How can I declare a function that returns a pointer to a function of its own type?: You can't quite do it directly. Use a cast, or wrap a struct around the pointer and return that. 6. My compiler is complaining about an invalid redeclaration of a function, but I only define it once. ANS. Calling an undeclared function declares it implicitly as returning int. 7.What can I safely assume about the initial values of variables which not explicitly initialized? ANS. Uninitialized variables with "static" duration start out as 0, as if programmer had initialized them. Variables with "automatic" duration, dynamically-allocated memory, start out containing garbage (with exception of calloc). 8.What's wrong with "char *p = malloc(10);" ? ANS. Function calls are not allowed in initializers for global or variables. are the and the

static

9: What is the difference between char a[] = "string"; and char *p = "string"; ? ANS: The first declares an initialized and modifiable array; the second declares a pointer initialized to a not-necessarilymodifiable constant string. 10: How do I initialize a pointer to a function? ANS: Use something like "extern int func(); int (*fp)() = func;" .

SECTION 2.Undefined behavior means *anything* can happen." prints 49. I have a program which works correctly. ANS: These operations are supported by all modern compilers.The variable i is both referenced and modified in the same expression. see the unabridged list. 17. 18. Why doesn't the code "a[i] = i++. using the offsetof() macro. How are structure passing and returning implemented? ANS: If you really need to know. I heard that structures could be assigned to variables and functions. Why? ANS: Check to see if a structure type declaration just before main() is missing its trailing semicolon. 2: What's the best way of implementing opaque (abstract) data types in C? ans: One good way is to use structure pointers which point to structure types which are not publicly defined. and Enumerations. passed to and from
5.. Unions. Can I pass constant values to functions which accept structure arguments? ANS: No. At the present time. 4. the second by a typedef name. there is little difference. Structures. i = i++. 6. How can I read/write structures from/to data files? ANS: It is relatively straightforward to use fread and fwrite. Why does sizeof report a larger size than I expect for a structure type? ANS: The alignment of arrays of structures must be preserved. printf("%d\n".. 3. causing main() to be declared as returning a structure. I came across some code that declared a structure with the last member an array of one element. 10. and typedef struct { . 12. good way for a compiler to implement structure comparison which is consistent with C's low-level flavor. 11. Is this legal or portable? ANS: An official interpretation has deemed that it is not strictly conforming with the C Standard. } x2. 7. 15. i++ * i++).
1: What's the difference between struct x1 { . or before other parts of the expression are evaluated. How can I determine the byte offset of a field within a structure? ANS: ANSI C defines the offsetof() macro. but not necessarily immediately after." work? ANS. 9. What is the difference between an enumeration and a set of preprocessor #defines? ANS. Is there an easy way to print enumeration values symbolically? ANS: No. The C Standard states that enumerations are compatible with integral types. }. Can I initialize unions? ANSI Standard C allows an initializer for the first-named member.
14. 8.. and then did some tricky allocation to make it act like the array had several elements. shouldn't it print 56? ANS: The operations implied by the postincrement and postdecrement operators ++ and -are performed at some time after the operand's former values are yielded and before the end of the expression." ever give 7? ANS. Under my compiler. How can I access structure fields by name at run time? ANS: Build a table of names and offsets.Why can't you compare structures? ANS. 16.. 13. How could the code "int i = 3. the code "int i = 7. but dumps core after it finishes. Regardless of the order of evaluation. C has no way of generating anonymous structure values. but K&R1 says not. which should be used if available. ANS.
. ? ans: The first structure is named by a tag. There is no single.

Why doesn't "((int *)p)++. Not portably.I want to use a char * pointer to step over some ints. 5. Operator precedence and explicit parentheses impose only a partial ordering on the evaluation of an expression.
SECTION 4. there is a special value -. 3. *p++ increments p. or in the variable part of variadic function calls) a constant 0 with an appropriate explicit cast is required." work? ANS. I have a function which accepts. 8. #defined as 0 (or((void *)0)). 4. or incremented with ++.null pointers valid? ANS. b = 1000. Why doesn't the code "int a = 1000. 2. not *p. Pointers
1. a pointer.How can I pass a constant like 5 to it? ANS:You will have to declare a temporary variable."? ANS. or comparison with one side a variable or expression of pointer type. 20. Does *p++ increment p. regardless of the internal representation of null pointers. Does C even have "pass by reference"? ANS. or what it points to? ANS. There is a special exception for those guaranteed. 7. ANS. which cannot be assigned to. What's wrong with "char *p. operators: left-to-right evaluation is
21. Null Pointers
1:What is this infamous null pointer. Don't precedence and parentheses dictate order of evaluation? ANS. NULL is simply a preprocessor macro.Not really. But what about the && and || operators? ANS.Is the abbreviated pointer comparison "if(p)" to test for non. and is supposed to initialize. 6." work? ANS: You must manually cast one of the operands to (long).which is distinguishable from all other pointer values and which is not the address of any object or function.For each pointer type.I have a function which accepts a pointer to an int. How do I get a null pointer in my programs? ANS. 4. which is used (as a stylistic convention. I've seen different methods used for calling functions via pointers.
. long int c = a * b.In other contexts (function arguments without prototypes.
SECTION 3. though it can be simulated. The extra parentheses and explicit * are now officially optional. which does not generally include the order of side effects. A "pointer context" is an initialization. To increment the value pointed to by p. assignment. A constant 0 in a pointer context is converted into a null pointer at compile time.Can I use a void ** pointer to pass a generic pointer to a function by reference? ANS.Yes.The pointer you declared is p. although some older implementations require them. because the compiler essentially rewrites it as "if(p != 0)" and goes on to convert 0 into the correct null pointer. ANS: The called function probably altered only the passed copy of the pointer. and by definition it yields an rvalue. and (in ANSI standard C) a function argument which has a prototype in scope declaring a certain parameter as being of pointer type. *p = malloc(10). a cast operator is a conversion operator. but the pointer in the caller remains unchanged. What is NULL and how is it #defined? ANS.the "null pointer" -. 2.In C.19. in preference to unadorned 0's) to generate null pointers.
3. anyway? ANS. The construction "if(p)" works. use (*p)++ .

and always cast them when they are used as arguments in function calls. This is strange.(The compiler makes the translation. So for an array a and pointer p. which is always #defined as 0 (or to help me build null
the null pointer is not? particular internal value does not with the character "0". 12. A "null pointer" is a language concept whose matter. as zero invites unwarranted assumptions. have done so.
1:I had the definition char a[6] in one source file. since it may be different from (char *)0. A null pointer is requested in source code preprocessor macro. Seriously. 10. but ANS. 14. the type of the resultant pointer is pointer-to-T. Not at all.The fact that null pointers are represented both in source code. via a null pointer. NULL is guaranteed to be 0. Arrays and Pointers. A reference like x[3] generates different code depending on whether x is an array or a pointer. How should NULL be defined on a machine which uses a nonzero bit pattern as the internal representation of a null pointer? ANS. the distinction is entirely stylistic. though valid. 8. I'm confused. Honeywell-Bull. to an invalid as Symbolics
location.so a constant zero is equally sufficient. Not in general. Arrays are not pointers." wouldn't that make function calls which pass an uncast NULL work? ANS.This trick. 9. wouldn't it be easier simply to require them to be represented internally by zeroes? ANS. A simple rule is. Why didn't it work? ANS. Such a requirement would accomplish little. Use extern char a[]. and CDC. upon seeing a 0.). "NULL" is a ((void *)0)).But wouldn't it be better to use NULL. A cast is still required to tell the compiler which kind of null pointer is required . 7.
." and then p[3] and a[3] will access the same element.". and in another I declared extern char *a.NULL is a constant zero. as well Lisp Machines. not the preprocessor. The same as on any other machine: as 0 (or ((void *)0)). 6. Machines manufactured by Prime. 2: But I heard that char a[] was identical to char *a.
SECTION 5. you can say "p = a. in case the value of NULL changes? ANS. Ans.5. I use the preprocessor macro "#define Nullptr(type) (type *)0" pointers of the correct type. I just can't understand all this null pointer stuff. "Always use `0' or `NULL' for null pointers. 15. Ans. 13.
11. 3: So what is meant by the "equivalence of pointers and arrays" in C? ANS: An lvalue of type array-of-T which appears in an expression decays into a pointer to its first element. or on some weird machine. which should I use? ANS.The use of a preprocessor macro (NULL) may seem to suggest that the value could change some day. It means that you've written. What does a run-time "null pointer assignment" error mean? ANS. does not buy much.The declaration extern char *a simply does not match the actual definition. ANS. No.Either. If NULL were defined as "((char *)0).The problem is that there are machines which use different internal representations for pointers to different types of data. have any actual machines really used nonzero null pointers? ANS. Given all the confusion surrounding null pointers.Why is there so much confusion surrounding null pointers? ANS.If NULL and 0 are equivalent as null pointer constants. and internally to most machines.

Not if the pointer points outside of the block of memory it is intended to access. 8. ANS." See the full list for code samples.What is the real difference between arrays and pointers? ANS. My compiler complained when I passed a two-dimensional array to a function expecting a pointer to a pointer. Yes.4. How can I set an array's size at run time? ANS. Usually. The (sizeof) operator reports the size of the pointer parameter which the function actually receives. and then initialize each pointer to a dynamically-allocated "row. How can I use statically.and dynamically-allocated multidimensional interchangeably when passing them to functions? ANS.What's the difference between array and &array? ANS. It's not particularly easy.e. ANS. if you can't assign to it? ANS.Why are array and pointer declarations interchangeable as function formal parameters? ANS. a two-dimensional array in C) decays into a pointer to an array. 12. How do I write functions which accept two-dimensional arrays when the "width" is not known at compile time? ANS. 17. 7. 15.How can an array be an lvalue. 9. 5. 14. Someone explained to me that arrays were really just constant pointers. I came across some "joke" code containing the "expression" 5["abcdef"] . An array is not a "modifiable lvalue. It is usually best to allocate an array of pointers. 16. but see the full list for some ideas.It's straightforward to use malloc() and a pointer. array subscripting is commutative in C.
. array? the array's
13. array dimensions must be compile-time constants. There is no single perfect method. An array of arrays (i.Arrays automatically allocate space which is fixed in size and location. How can I declare local arrays of a size matching a passed-in ANS. It's supposed to be a convenience. The rule by which arrays decay into pointers is not applied recursively. not a pointer to a pointer. 11.". How can this be legal C? ANS. An array name is "constant" in that it cannot be assigned to. arrays
18. The type.but an array is *not* a pointer. Consider using a pointer to one of elements instead. The array subscripting operation a[e] is defined as being identical to *((a)+(e)).How do I declare a pointer to an array? ANS. You can't. you don't want to. 6. pointers are dynamic.How can I dynamically allocate a multidimensional array? ANS. 10.Can I simulate a non-0-based array with a pointer? ANS. Why doesn't (sizeof) properly report the size of an array which is a parameter to a function? ANS.

Make sure you aren't using more memory than you malloc'ed.can you? ANS. exactly 1. The pointer variable answer() has not been set to point to any valid storage." work? ANS. ANS. Before ANSI/ISO C. apparently somewhere down inside malloc." but I got strange results.
. instead of a pointer. Why does so much code leave out the multiplication by sizeof(char) when allocating strings? ANS. I have a function that is supposed to return a string. do I also have to free each subsidiary pointer? ANS. s2).h>?. Some early documentation implied otherwise. Why can I only seem to malloc() 640K or so? ANS. 6. 9. Is this legal? ANS. No. 8. Why am I getting "warning: assignment of pointer from integer lacks a cast" for calls to malloc()? ANS. My program is crashing. gets(answer). I can't get strcat() to work.When I call malloc() to allocate memory for a local pointer. I tried "char *s3 = strcat(s1. C's pass-by-value semantics mean that called functions can never permanently change the values of their arguments. 14. but the claim is no longer valid.
The
2.Make sure that the pointed-to memory is properly (i. 5. simplest way to correct this fragment is to use a local array. I'm allocating a large array for some numeric work. the returned string is garbage. How am I supposed to know to allocate things? ANS. 4. especially for strings (which need strlen(str) + 1 bytes). these casts were required to silence certain warnings. 10. Memory Allocation
1: Why doesn't the code "char *answer.e.SECTION 6. if only to make sure that the compiler is doing it for you. 12. when using pointers you *always* have to consider memory allocation. do I have to explicitly free() it? ANS. 11. When I free a dynamically-allocated structure containing pointers. ANS. Make sure the number you're trying to pass to malloc() isn't bigger than a size_t can hold. 7.Why isn't a pointer null after calling free()? ANS. by definition. it can be difficult to use more than 640K with any degree of transparency. Yes. Why does some code carefully cast the values returned by malloc to the pointer type being allocated? ANS. but when it returns to its caller. ANS. not locally) allocated. In general. Again. the main problem here is that space for the concatenated result is not properly allocated. 3: But the man page for strcat() says that it takes two char *'s as arguments. 15. Yes.You can't use dynamically-allocated memory after you free it. 13. but malloc() is acting strangely. Have you #included <stdlib.Because sizeof(char) is.Under the segmented architecture of PC compatibles. ANS.It's hard to say. I've got 8 meg of memory in my PC. I've heard that some operating systems don't actually allocate malloc'ed memory until the program tries to use it.

strcat() concatenates *strings*. 4:What's the best way to write a multi-statement macro?
. 5: Why is sizeof('a') not 1? ANS:Character constants in C are of type int.
1: What is the right type to use for Boolean values in C? ANS.Usestrcpy() instead. Boolean Expressions and Variables.
SECTION 8. alloca() allocates memory which is automatically freed when the function which called alloca() returns.Must I free allocated memory before the program exits? ANS.
SECTION 7. although several earlier implementations do not support it. 4:How can I get the numeric (character set) value corresponding to a character? ANS:In C. Characters and Strings. 2:Why won't the test if(string == "value") correctly compare string against the value? ANS:It's comparing pointers." work? Ans.16. What's the difference between calloc() and malloc()? ANS. 17. alloca() cannot be written portably. 3:Is if(p). What is alloca() and why is its use discouraged? ANS. Is it legal to pass a null pointer as the first argument to realloc()? ANS. size of each block allocated and
19.Why doesn't my program's memory usage go down when I free memory? ANS. and initializes the allocated memory to all-bits-0. To compare two strings. 21.So can I query the malloc package to find out how big an allocated block is? ANS. where p is a pointer. '!'). see the full list for some discussion. 22. Not portably. valid? ANS:Yes. (This is *not* true for some library routines such as isalpha.There's no one right answer. ANSI C sanctions this usage. it is guaranteed to be 1 or 0. is difficult to implement on machines without a stack. and you can't assign arrays directly. 2:What if a built-in logical or relational operator "returns" something other than 1? ANS:When a Boolean value is generated by a built-in operator. not characters.Most implementations of malloc/free do not return freed memory to the operating system. calloc() takes two arguments.You shouldn't have to. use strcmp(). 20. 18.). if you have the character. and fails under certain conditions if implemented simply. you have its value.
1:Why doesn't "strcat(string. How does free() know how many bytes to free? ANS. The malloc/free implementation remembers the returned. 3:Why can't I assign strings to character arrays? ANS:Strings are arrays.

16: I have some old code that tries to construct identifiers with a macro like "#define Paste(a. . try #defining several manifest constants and implementing conditionals on those. b) a/**/b".
. to define something two different ways? ANS: No. not the definition . but it doesn't work any more.h files and what should I put in them? ANS: Header files (also called ". no. and thus receives considerable debate.h files") should generally contain common declarations and macro. see the full list for some discussion. } while(0) /* (no trailing . rmifdef.) */. ANS: Try the ANSI token-pasting operator ##.ANS: #define Func() do {stmt1. without preprocessing everything? ANS: Look for a program called unifdef.. try extracting printable strings from the compiler or preprocessor executable. 14: How can I preprocess some code to remove selected conditional compilations. but not variable or function definitions. ANS: Consider writing your own little special-purpose preprocessing tool. n)). and typedef definitions. 11: Can I use an #ifdef in a #define line. 8: I'm getting strange syntax errors on the very first declaration in a file.. 9: How can I construct preprocessor #if expressions which compare strings? ANS: You can't do it directly. 12: Is there anything like an #ifdef for typedefs? ANS: Unfortunately. structure. 6:Is it acceptable for one header file to #include another? ANS:It's a question of style. ANS:Perhaps there's a missing semicolon at the end of the last declaration in the last header file you're #including.
5: What are . Note that the parentheses around printf's argument list are in the macro call. 17: I've got this tricky preprocessing I want to do and I can't figure out a way to do it. instead. 15: How can I list all of the pre#defined identifiers? ANS: If the compiler documentation is unhelpful. printf args) if(n != 0) DEBUG(("n is %d\n". 18: How can I write a macro which takes a variable number of arguments? ANS: Here is one popular trick. or scpp. 7:Where are header ("#include") files searched for? ANS:The exact behavior is implementation-defined. stmt2. but it looks fine. 10: Does the sizeof operator work in preprocessor #if directives? ANS: No. 13: How can I use a preprocessor #if expression to detect endianness? ANS: You probably can't. #define DEBUG(args) (printf("DEBUG: ").

11: But what about main's third argument.159-1989. the latter declares constant pointer to a character. 8: What's the difference between "const char *"p and "char * const" p? ANS: The former declares a pointer to a constant character. a
9: Why can't I pass a char ** to a function which expects a const char **? ANS:The rule which permits slight mismatches in qualified pointer assignments is not applied recursively. 4: My ANSI compiler is complaining about prototype mismatches for parameters declared float. CO. the problem is that its caller may not even be able to *call* it correctly. or from any national standards body. returns no
. ANS:It doesn't matter whether main() returns or not. or republished within one or more books. the American National Standards Institute (ANSI) commissioned a committee to standardize the C language. "Narrow" types are treated differently according to which syntax is used. and has since been adopted as ISO/IEC 9899:1990. and later amended." give me a warning message? ANS: A structure declared (or even mentioned) for the first time within a prototype cannot be compatible with other structures declared in the same source file. 12: I believe that declaring void main() can't fail.3). 3: Where can I get information about updates to the Standard? ANS: See the full list for pointers.
ANSI/ISO Standard
1: What is the "ANSI C Standard?" ANS: In 1983." with the old-style definition "int func(x) float x. Their work was ratified as ANS X3. since I'm calling exit() instead of returning. 5: Can you mix old-style and new-style function syntax? ANS: Doing so is currently perfectly legal. or by using either new-style (prototype) or old-style syntax consistently. 14: How do I get the ANSI "stringizing" preprocessing operator `#' to stringize the macro's value instead of its name? ANS: You can use a two-step #definition to force a macro to be expanded as well as stringized.SECTION 9. 10: Can I declare main() as void. or from Global Engineering Documents in Englewood. 6: Why does the declaration "extern f(struct x *p). or from ISO in Geneva. ANS: You have mixed the new-style prototype declaration "extern int func(float). 15: What does the message "warning: macro replacement within a string literal" mean? ANS: Some pre-ANSI compilers/preprocessors expanded macro parameters even inside string literals and character constants. 13: The book I've been using always uses void main(). envp? ANS:It's a non-standard (though common) extension.". for most argument types (see question 11. to shut off these annoying "main value" messages? ANS: No. 2: How can I get a copy of the Standard? ANS:Copies are available from ANSI in New York. 7: Why can't I use const values in initializers and array dimensions? ANS: The value of a const-qualified object is *not* a constant expression in the full sense of the term. See the unabridged list for details. ANS:It's wrong. This problem can be fixed by avoiding narrow types.

well-defined "escape hatch" which can be used for extensions. 25: Why are some ANSI/ISO Standard library routines showing up as though I've got an ANSI compiler? ANS: Perhaps you don't have ANSI-compatible headers and libraries. ignore the distinctions. ANS: Under ANSI C. ANS: In most of these cases. 27: Why won't frobozz-cc. 19: Is char a[3] = "abc". 18: What does "#pragma once" mean? ANS: It is an extension implemented by some preprocessors to help make header files idempotent. in ANSI C.
. and no unterminated comments or quotes (i. 22: What should malloc(0) do? ANS: The behavior is implementation-defined. no single apostrophes). and undefined behavior? ANS: If you're writing portable code. 29: I'm appalled that the ANSI Standard leaves so many issues undefined.e. ANS: A compiler may do anything it likes when faced with undefined behavior. 20: Why can't I perform arithmetic on a void * pointer? ANS:The compiler doesn't know the size of the pointed-to objects. unspecified. which claims to be ANSI compliant. including doing what you expect. 24: My compiler is rejecting the simplest possible test programs. 21:What's the difference between memcpy() and memmove()? ANS: memmove() offers guaranteed behavior if the source overlap.16: I'm getting strange syntax errors inside lines I've #ifdeffed out. the Standard is simply codifying existing practice. 28: What's the difference between implementation-defined. 17: What are #pragmas ? ANS: The #pragma directive provides a single. undefined." This means that there must be no newlines inside quotes. #ifdeffed-out text must still consist of "valid preprocessing tokens.Otherwise. and got the results I expected.with all kinds of syntax errors. 30: I just tried some allegedly-undefined code on an ANSI-conforming compiler. ANS:Perhaps it is a pre-ANSI compiler. accept this code? ANS: Are you sure that the code being rejected doesn't rely on some non-Standard extension?. or for automatically generating prototypes? ANS: See the full list for details. see the full list. even and destination arguments
26: Does anyone have a tool for converting old-style C programs to ANSI C. 23: Why does the ANSI Standard not guarantee more than six case insensitive characters of external identifier significance? ANS: The problem is older linkers which cannot be forced (by mere words in a Standard) to upgrade. legal? ANS: Yes.

1:What's wrong with the code "char c. ANS: scanf() tends to "jam" on bad input since it does not discard it.
3: My program's prompts and intermediate output don't always show up on the screen. outfp). 15: Why does everyone say not to use gets()? ANS: It cannot be prevented from overflowing the input buffer. 9: Why doesn't the code "double d. 13:Why does everyone say not to use scanf()? What should I use instead? ANS: scanf() has a number of problems. n).h>). it seems to hang until I type one extra line of input. scanf() uses %lf for double.18: I'm reading a number with scanf %d and then a string with gets(). i) work? ANS: The arguments you pass to scanf() must always be pointers. it's easier to read entire lines and then interpret them. 8: Why doesn't the call scanf("%d". It is only meaningful for a program to inspect the contents of errno after an error has been reported. ANS: Try using "%d" instead of "%d\n". Usually. 5:How can printf() use %f for type double. Stdio. but sometimes it seems to go into an infinite loop. infp). 4: How can I print a '%' character with printf? ANS: "%%". 6: How can I implement a variable field width with printf? ANS: Use printf("%*d".SECTION 9.
... but the compiler seems to be skipping the call to gets()!: scanf() and gets() do not work well together. }" work? ANS:EOF is only indicated *after* an input routine has reached end-of-file. width. 16: Why does errno contain ENOTTY after a call to printf()? ANS: Don't worry about it. scanf("%f". 7: How can I print numbers with commas separating the thousands? ANS:There is no standard routine (but see <locale. if scanf() requires %lf? ANS: C's "default argument promotions" mean that values of type float are promoted to double." work? ANS: Unlike printf()."? ANS: The variable to hold getchar's return value must be an int. fputs(buf. ANS:It's best to use an explicit fflush(stdout) whenever output should definitely be visible. 11: When I read numbers from the keyboard with scanf "%d\n". 17: What's the difference between fgetpos/fsetpos and ftell/fseek? ANS: fgetpos() and fsetpos() use a special typedef which may allow them to work with larger files than ftell() and fseek(). &d). 10: How can I specify a variable width in a scanf() format string? ANS:You can't. and %f for float. 12: I'm re-prompting the user if scanf() fails.. MAXLINE. 2:Why won't the code "while(!feof(infp)) {fgets(buf. while((c = getchar()) != EOF) . 14: How can I tell how much destination buffer space I'll need for an arbitrary sprintf call? How can I avoid overflowing the destination buffer with sprintf()? ANS:There are not (yet) any good answers to either of these excellent questions.

LIBRARY FUNCTIONS. yielding char *'s which can be usefully compared. but the compiler is complaining that the function is of the wrong type for qsort(). 9: How can I sort more data than will fit in memory? ANS: You want an "external sort". but it's not working. converts them to char **. 8: How can I sort a linked list? Ans: Algorithms like insertion sort and merge sort work well. 14:I need a random number generator. how can I get the original stream back? ANS: There isn't a good way. ANS: The Standard C library has one: rand(). 5:I need some code to do regular expression and wildcard matching. or you in order as you build it. but it's not working. see the full list for details. 13: How can I perform calendar manipulations? ANS: The ANSI/ISO Standard C mktime() and difftime() functions provide some support for both problems. can keep the list
. 2: Why does strncpy() not always write a '\0'? ANS: For mildly-interesting historical reasons. ANS: Be sure to call fseek between reading and writing. 20:How can I redirect stdin or stdout from within a program? ANS: Use freopen(). No standard routine exists to parse strings.18: Will fflush(stdin) flush unread characters from the standard input stream? ANS: No. 21:Once I've used freopen(). 6:I'm trying to sort an array of strings with qsort(). Try avoiding freopen. ANS: regexp libraries abound. and dereferences them. by using fopen mode "r+". 7: Now I'm trying to sort an array of structures. ctime(). ANS: The comparison function must be declared as accepting "generic pointers" (const void *) which it then converts to structure pointers. and/or localtime() functions. 11:How can I get the time of day in a C program? ANS: Just use the time(). 22: How can I read a binary data file properly? ANS: Be sure to specify "rb" mode when calling fopen(). 3: Why do some versions of toupper() act strangely if given an upper-case letter? ANS: Older versions of toupper() and tolower() did not always work as expected in this regard. 12:How can I convert a struct tm or a string into a time_t? ANS:The ANSI mktime() routine converts a struct tm to a time_t. ANS: You'll have to write a "helper" comparison function which takes two generic pointer arguments. using strcmp() as the comparison function.
1: How can I convert numbers to strings? ANS: Just use sprintf().
SECTION 10. 4:How can I split up a string into whitespace-separated fields? ANS: Try strtok(). see the full list for details. 19: I'm trying to update a file in place.

ANS: You may have to explicitly ask for the correct libraries to be searched.h>. even though I'm requesting the right libraries. try (int)(x + 0.1. 17:I need a random true/false value.) giving me crazy numbers? ANS: Make sure that you have #included <math.5) . Why do I get "undefined external" errors for library functions? Some semistandard functions have been renamed or replaced over the years. 8:The pre-#defined constant M_PI seems to be missing from ANS: That constant is not standard.15:How can I get random integers in a certain range? ANS: One method is something like (int)((double)rand() / ((double)RAND_MAX + 1) * N)..
20:I get errors due to library functions being undefined even though I #include the right header files.. you must search the libraries last.1 decimal) are not exactly representable in base 2. 21:I'm still getting errors due to library functions being undefined. 0.
. 3: I keep getting "undefined: sin" compilation errors. FLOATING POINT. 1. usually. 1. 4: My floating-point calculations are acting strangely and giving me different answers on different machines. ANS: You can call srand() to seed the pseudo-random number generator with a truly random initial value. If the problem isn't that simple. so I'm just taking rand() % 2. too. but see the full list for ideas. 0. 5: What's a good way to check for "close enough" floating-point equality? ANS: The best way is to use an accuracy threshold which is relative to the magnitude of the numbers being compared.
9:How do I test for IEEE NaN and other special values? ans:There is not yet a portable way. see the full list for a brief explanation. and correctly declared other functions returning double.
SECTION 11. ANS: Make sure you're actually linking with the math library. 19: some ANS: full distribution?
I'm trying to port this old program.0999999? ANS: Most computers use base 2 for floating-point numbers. see the list for details.h>. 7:Where is C's exponentiation operator? ANS:Try using the pow() function. 22:What does it mean when the linker says that _end is undefined? ANS:You generally get that message only when other things are undefined. or any good programming book for a better one. why is printf() printing it as 3. 16:Each time I run my program. ANS: Try using the higher-order bits 18:How can I generate random numbers with a normal or Gaussian ANS:See the longer versions of this list for ideas. 2: Why is sqrt(144. <math. ANS: First. see question 2 above.
1:When I set a float variable to 3. 6:How do I round numbers? ANS:For positive numbers. and many fractions (including 0. ANS:Library search order is significant. but it's alternating 0. I get the same sequence of numbers back from rand().

SECTION 12. 12:How can I write a function which takes a variable number of arguments and passes them to some other function ? ANS:In general. you cannot.h>. except (in effect) when they are used as array initializers. and passes them to printf() to do most of the work? ANS:Use vprintf(). What can I do? ANS:There's an older header.10:What's a good way to implement complex numbers in C? ANS:It is straightforward to define a simple structure and some arithmetic functions to manipulate them.h> before calling printf(). double). 3:Why don't function prototypes guard against mismatches in printf's arguments? ANS:Function prototypes do not provide any information about the number and types of variable arguments.h> header. 9:My compiler isn't letting me declare a function that accepts *only* variable arguments. it shouldn't have. 14:Why does the code "char *p = "hello. ANS:Use a typedef.
1:I heard that you have to #include <stdio. 8:How can I discover how many arguments a function was actually called with? ANS:Any function which takes a variable number of arguments must be able to determine *from the arguments' values* how many of them there are. 15:What does "Segmentation violation" mean? ANS:It generally means that your program tried to access memory invariably as a result of stack corruption or improper pointer use.h>. 5:How can I write a function that takes a format string and a variable arguments. world!". or vsprintf(). and float is promoted to double. ANS: Standard C requires at least one fixed argument. vscanf and the like are not standard. 7:I have a pre-ANSI compiler. p[0] = 'H'. <varargs. Variable-Length Argument Lists. number of
6:How can I write a function analogous to scanf(). vfprintf(). float)" working? ANS: Because the "default argument promotions" apply in variable length argument lists. like printf(). types char and short int are promoted to int. 10:Why isn't "va_arg(argp." ANS:You may have to insert an extra call to a floating-point library routine to force loading of floating-point support. 11:I can't get va_arg() to pull in an argument of type pointer-to-function. you should always use va_arg(argp. 11: I'm having trouble with a Turbo C program which crashes and says something like "floating point formats not linked. without <stdarg. that calls scanf() to do most of the work? ANS:Unfortunately. Why?
2:How can %f be used for both float and double arguments in printf()? ANS:In variable-length argument lists. which offers about the same functionality. 13:How can I call a function with an argument list built up at run time? ANS:You can't. ANS: So that a proper prototype for printf() will be in scope.
. 4:How can I write a function that takes a variable number of arguments? ANS: Use the <stdarg." crash? ANS: String literals are not modifiable.

The sequences /* and */ are not special within double-quoted strings. 9:What is the most efficient way to count the number of bits which are set in a value? ANS:Many "bit-fiddling" problems like this one can be sped up and streamlined using lookup tables. 16:Why doesn't C have nested functions? ANS:They were deliberately left out of C as a simplification. with a few macros to access the desired bit at the proper index. 2:How do I access command-line arguments? ANS: Via main()'s argv parameter. or have the function return a structure containing the desired values. you may be able to select a base.
1:How can I return multiple values from a function? ANS:Either pass pointers to several locations which the function can fill in. integers are already in binary. 12:Is there a way to switch on strings? ANS:Not directly. 5:How can I implement sets or arrays of bits? ANS: Use arrays of char or int. 17: How can I call FORTRAN (C++. 7:How can I convert integers to binary or hexadecimal? ANS:Internally. LISP) functions from C? ANS:The answer is entirely dependent on the machine and the specific calling sequences of the various compilers in use. 3:How can I write data files which can be read on other machines with different data formats? ANS:The most portable solution is to use text files. 15: Why don't C comments nest? Are they legal inside quoted strings? ANS: C comments don't nest because PL/I's comments don't either. Miscellaneous. ranges or arbitrary expressions)? ANS:No. 4:How can I call a function. Pascal. given its name as a string? ANS:The most straightforward thing to do is to maintain a correspondence table of names and function pointers. 6:How can I determine whether a machine's byte order is big-endian or little-endian? ANS:The usual tricks involve pointers or unions. 13:Is there a way to have non-constant case labels (i. on both counts. During I/O. BASIC.
SECTION 13.16:What is "Hungarian Notation"? ANS: It's a naming convention which encodes things about a variable's type in its name.e. 18:Does anyone know of a program for converting Pascal or FORTRAN to C? character
. 14: Are the outer parentheses in return statements really optional? ANS: Yes. Ada. 10:What's the best way of making my program efficient? ANS:By picking good algorithms and implementing them carefully. 11:Are pointers really faster than arrays? How much do function calls slow things down? ANS:Precise answers to these and many similar questions depend on the processor and compiler in use. 8:Can I use base-2 constants (something like 0b101010)? Is there a printf() format for binary? ANS: No.

which was a simplification of CPL. which was inspired by BCPL.ANS:Several freely distributable programs are available. but it has been withdrawn.html . namely the full list for details.named entry points.Steve Summit scs@eskimo. anyway? ANS: C was derived from B.com/~scs/C-faq/top. It is intended to complement the use of thetext and is protected by international copyright laws. p2c. or some code in the full list. 23:Where does the name "C" come from. Theis made available here and may be accessed freely for personalbut may not be republished without permissioN
.comarticle is Copyright 1990-1996 by Steve Summit. C++ is not a strict superset of C. 22:What was the entry keyword mentioned in K&R1? ANS:It was reserved to allow functions with multiple. and f2c. An extended version has been published by Addison-Wesley as _C Programming FAQs: Frequently Asked Questions_ISBN 0-201-84519-9).
ptoc. Zeller's congruence. differently. for easier searching.from the book _C Programming FAQs: Frequently Asked Questions_made available here by permission of the author and the publisher asservice to the community. 21:How can I find the day of the week given the date? ANS: Use mktime().
A hypertext version of this FAQ list is available at http://www.See
20:What is hashing? ANS:A mapping of strings (or other data structures) to integers.eskimo. 19: Can I use a C++ compiler to compile C code? ANS:Not necessarily.