1. What is indirection? Answer: If you declare a variable, its name is a direct reference to its value. If you have a pointer to a variable, or any other object in memory, you have an indirect reference to its value. If p is a pointer, the value of p is the address of the object. *p means "apply the indirection operator to p"; its value is the value of the object that p points to. (Some people would read it as "Go indirect on p.") *p is an lvalue; like a variable, it can go on the left side of an assignment operator, to change the value. If p is a pointer to a constant, *p is not a modifiable lvalue; it can't go on the left side of an assignment. Consider the following program. It shows that when p points to i, *p can appear wherever i can. ``````#include int main() { int i; int *p; i = 5; p = & i; /* now *p == i */ printf("i=%d, p=%P, *p=%d\n", i, p, *p); *p = 6; /* same as i = 6 */ printf("i=%d, p=%P, *p=%d\n", i, p, *p); return 0; } `````` After p points to i (p = &i), you can print i or *p and get the same thing. You can even assign to *p, and the result is the same as if you had assigned to i. Report errors ... Name : Email:

 2. How many levels of pointers can you have? Answer: The answer depends on what you mean by "levels of pointers." If you mean "How many levels of indirection can you have in a single declaration?" the answer is "At least 12." int i = 0; int *ip01 = & i; int **ip02 = & ip01; int ***ip03 = & ip02; int ****ip04 = & ip03; int *****ip05 = & ip04; int ******ip06 = & ip05; int *******ip07 = & ip06; int ********ip08 = & ip07; int *********ip09 = & ip08; int **********ip10 = & ip09; int ***********ip11 = & ip10; int ************ip12 = & ip11; ************ip12 = 1; /* i = 1 */ If you mean "How many levels of pointer can you use before the program gets hard to read," that's a matter of taste, but there is a limit. Having two levels of indirection (a pointer to a pointer to something) is common. Any more than that gets a bit harder to think about easily; don't do it unless the alternative would be worse. If you mean "How many levels of pointer indirection can you have at runtime," there's no limit. This point is particularly important for circular lists, in which each node points to the next. Your program can follow the pointers forever. Consider the following program "A circular list that uses infinite indirection". ``````/* Would run forever if you didn't limit it to MAX */ #include struct circ_list { char value[ 3 ]; /* e.g., "st" (incl '\0') */ struct circ_list *next; }; struct circ_list suffixes[] = { "th", & suffixes[ 1 ], /* 0th */ "st", & suffixes[ 2 ], /* 1st */ "nd", & suffixes[ 3 ], /* 2nd */ "rd", & suffixes[ 4 ], /* 3rd */ "th", & suffixes[ 5 ], /* 4th */ "th", & suffixes[ 6 ], /* 5th */ "th", & suffixes[ 7 ], /* 6th */ "th", & suffixes[ 8 ], /* 7th */ "th", & suffixes[ 9 ], /* 8th */ "th", & suffixes[ 0 ], /* 9th */ }; #define MAX 20 int main() { int i = 0; struct circ_list *p = suffixes; while (i <= MAX) { printf( "%d%s\n", i, p->value ); ++i; p = p->next; } return 0; } `````` Each element in suffixes has one suffix (two characters plus the terminating NUL character) and a pointer to the next element. next is a pointer to something that has a pointer, to something that has a pointer, ad infinitum. The example is dumb because the number of elements in suffixes is fixed. It would be simpler to have an array of suffixes and to use the i%10'th element. In general, circular lists can grow and shrink. Report errors ... Name : Email:

 3. What is a null pointer? Answer: There are times when it's necessary to have a pointer that doesn't point to anything. The macro NULL, defined in , has a value that's guaranteed to be different from any valid pointer. NULL is a literal zero, possibly cast to void* or char*. Some people, notably C++ programmers, prefer to use 0 rather than NULL. You can't use an integer when a pointer is required. The exception is that a literal zero value can be used as the null pointer. (It doesn't have to be a literal zero, but that's the only useful case. Any expression that can be evaluated at compile time, and that is zero, will do. It's not good enough to have an integer variable that might be zero at runtime.) Report errors ... Name : Email:

 4. When is a null pointer used? Answer: The null pointer is used in three ways: 1. To stop indirection in a recursive data structure. 2. As an error value. 3. As a sentinel value. 1. Using a Null Pointer to Stop Indirection or Recursion Recursion is when one thing is defined in terms of itself. A recursive function calls itself. The following factorial function calls itself and therefore is considered recursive: ``````/* Dumb implementation; should use a loop */ unsigned factorial( unsigned i ) { if ( i == 0 || i == 1 ) { return 1; } else { return i * factorial( i - 1 ); } } `````` A recursive data structure is defined in terms of itself. The simplest and most common case is a (singularly) linked list. Each element of the list has some value, and a pointer to the next element in the list: ``````struct string_list { char *str; /* string (in this case) */ struct string_list *next; }; `````` There are also doubly linked lists (which also have a pointer to the preceding element) and trees and hash tables and lots of other neat stuff. You'll find them described in any good book on data structures. You refer to a linked list with a pointer to its first element. That's where the list starts; where does it stop? This is where the null pointer comes in. In the last element in the list, the next field is set to NULL when there is no following element. To visit all the elements in a list, start at the beginning and go indirect on the next pointer as long as it's not null: ``````while ( p != NULL ) { /* do something with p->str */ p = p->next; } `````` Notice that this technique works even if p starts as the null pointer. 2. Using a Null Pointer As an Error Value The second way the null pointer can be used is as an error value. Many C functions return a pointer to some object. If so, the common convention is to return a null pointer as an error code: ``````if ( setlocale( cat, loc_p ) == NULL ) { /* setlocale() failed; do something */ /* ... */ } `````` This can be a little confusing. Functions that return pointers almost always return a valid pointer (one that doesn't compare equal to zero) on success, and a null pointer (one that compares equal to zero) pointer on failure. Other functions return an int to show success or failure; typically, zero is success and nonzero is failure. That way, a "true" return value means "do some error handling": ``````if ( raise( sig ) != 0 ) { /* raise() failed; do something */ /* ... */ } `````` The success and failure return values make sense one way for functions that return ints, and another for functions that return pointers. Other functions might return a count on success, and either zero or some negative value on failure. As with taking medicine, you should read the instructions first. Using a Null Pointer As a Sentinel Value The third way a null pointer can be used is as a "sentinel" value. A sentinel value is a special value that marks the end of something. For example, in main(), argv is an array of pointers. The last element in the array (argv[argc]) is always a null pointer. That's a good way to run quickly through all the elements: ``````/* A simple program that prints all its arguments. It doesn't use argc ("argument count"); instead, it takes advantage of the fact that the last value in argv ("argument vector") is a null pointer. */ #include #include int main( int argc, char **argv) { int i; printf("program name = \"%s\"\n", argv[0]); for (i=1; argv[i] != NULL; ++i) printf("argv[%d] = \"%s\"\n", i, argv[i]); assert(i == argc); return 0; } `````` Report errors ... Name : Email:

 5. What is a void pointer? Answer: A void pointer is a C convention for "a raw address." The compiler has no idea what type of object a void pointer "really points to." If you write int *ip; ip points to an int. If you write void *p; p doesn't point to a void! In C and C++, any time you need a void pointer, you can use another pointer type. For example, if you have a char*, you can pass it to a function that expects a void*. You don't even need to cast it. In C (but not in C++), you can use a void* any time you need any kind of pointer, without casting. (In C++, you need to cast it.) Report errors ... Name : Email:

 6. When is a void pointer used? Answer: A void pointer is used for working with raw memory or for passing a pointer to an unspecified type. Some C code operates on raw memory. When C was first invented, character pointers (char *) were used for that. Then people started getting confused about when a character pointer was a string, when it was a character array, and when it was raw memory. For example, strcpy() is used to copy data from one string to another, and strncpy() is used to copy at most a certain length string to another: char *strcpy( char *str1, const char *str2 ); char *strncpy( char *str1, const char *str2, size_t n ); memcpy() is used to move data from one location to another: void *memcpy( void *addr1, void *addr2, size_t n ); void pointers are used to mean that this is raw memory being copied. NUL characters (zero bytes) aren't significant, and just about anything can be copied. Consider the following code: ``````#include "thingie.h" /* defines struct thingie */ struct thingie *p_src, *p_dest; /* ... */ memcpy( p_dest, p_src, sizeof( struct thingie) * numThingies ); `````` This program is manipulating some sort of object stored in a struct thingie. p1 and p2 point to arrays, or parts of arrays, of struct thingies. The program wants to copy numThingies of these, starting at the one pointed to by p_src, to the part of the array beginning at the element pointed to by p_dest. memcpy() treats p_src and p_dest as pointers to raw memory; sizeof( struct thingie) * numThingies is the number of bytes to be copied. Report errors ... Name : Email:

 7. Can you subtract pointers from each other? Why would you? Answer: If you have two pointers into the same array, you can subtract them. The answer is the number of elements between the two elements. Consider the street address analogy presented in the introduction of this chapter. Say that I live at 118 Fifth Avenue and that my neighbor lives at 124 Fifth Avenue. The "size of a house" is two (on my side of the street, sequential even numbers are used), so my neighbor is (124-118)/2 (or 3) houses up from me. (There are two houses between us, 120 and 122; my neighbor is the third.) You might do this subtraction if you're going back and forth between indices and pointers. You might also do it if you're doing a binary search. If p points to an element that's before what you're looking for, and q points to an element that's after it, then (q-p)/2+p points to an element between p and q. If that element is before what you want, look between it and q. If it's after what you want, look between p and it. (If it's what you're looking for, stop looking.) You can't subtract arbitrary pointers and get meaningful answers. Someone might live at 110 Main Street, but I can't subtract 110 Main from 118 Fifth (and divide by 2) and say that he or she is four houses away! If each block starts a new hundred, I can't even subtract 120 Fifth Avenue from 204 Fifth Avenue. They're on the same street, but in different blocks of houses (different arrays). C won't stop you from subtracting pointers inappropriately. It won't cut you any slack, though, if you use the meaningless answer in a way that might get you into trouble. When you subtract pointers, you get a value of some integer type. The ANSI C standard defines a typedef, ptrdiff_t, for this type. (It's in .) Different compilers might use different types (int or long or whatever), but they all define ptrdiff_t appropriately. Below is a simple program that demonstrates this point. The program has an array of structures, each 16 bytes long. The difference between array[0] and array[8] is 8 when you subtract struct stuff pointers, but 128 (hex 0x80) when you cast the pointers to raw addresses and then subtract. If you subtract 8 from a pointer to array[8], you don't get something 8 bytes earlier; you get something 8 elements earlier. ``````#include #include struct stuff { char name[16]; /* other stuff could go here, too */ }; struct stuff array[] = { { "The" }, { "quick" }, { "brown" }, { "fox" }, { "jumped" }, { "over" }, { "the" }, { "lazy" }, { "dog." }, { "" } }; int main() { struct stuff *p0 = & array[0]; struct stuff *p8 = & array[8]; ptrdiff_t diff = p8 - p0; ptrdiff_t addr_diff = (char*) p8 - (char*) p0; /* cast the struct stuff pointers to void* */ printf("& array[0] = p0 = %P\n", (void*) p0); printf("& array[8] = p8 = %P\n", (void*) p8); /* cast the ptrdiff_t's to long's (which we know printf() can handle) */ printf("The difference of pointers is %ld\n", (long) diff); printf("The difference of addresses is %ld\n", (long) addr_diff); printf("p8 - 8 = %P\n", (void*) (p8 - 8)); printf("p0 + 8 = %P (same as p8)\n", (void*) (p0 + 8)); return 0; } `````` Report errors ... Name : Email:

 8. Is NULL always defined as 0(zero)? Answer: NULL is defined as either 0 or (void*)0. These values are almost identical; either a literal zero or a void pointer is converted automatically to any kind of pointer, as necessary, whenever a pointer is needed (although the compiler can't always tell when a pointer is needed). Report errors ... Name : Email:

 9. Is NULL always equal to 0(zero)? Answer: The answer depends on what you mean by "equal to." If you mean "compares equal to," such as ``````if ( /* ... */ ) { p = NULL; } else { p = /* something else */; } /* ... */ if ( p == 0 ) `````` then yes, NULL is always equal to 0. That's the whole point of the definition of a null pointer. If you mean "is stored the same way as an integer zero," the answer is no, not necessarily. That's the most common way to store a null pointer. On some machines, a different representation is used. The only way you're likely to tell that a null pointer isn't stored the same way as zero is by displaying a pointer in a debugger, or printing it. (If you cast a null pointer to an integer type, that might also show a nonzero value.) Report errors ... Name : Email:

 10. What does it mean when a pointer is used in an if statement? Answer: Any time a pointer is used as a condition, it means "Is this a non-null pointer?" A pointer can be used in an if, while, for, or do/while statement, or in a conditional expression. It sounds a little complicated, but it's not. Take this simple case: ``````if ( p ) { /* do something */ } else { /* do something else */ } `````` An if statement does the "then" (first) part when its expression compares unequal to zero. That is, if ( /* something */ ) is always exactly the same as this: if ( /* something */ != 0 ) That means the previous simple example is the same thing as this: ``````if ( p != 0 ) { /* do something (not a null pointer) */ } else { /* do something else (a null pointer) */ } `````` This style of coding is a little obscure. It's very common in existing C code; you don't have to write code that way, but you need to recognize such code when you see it. Report errors ... Name : Email: