Answers to Chapter 13 Review Questions -------------------------------------- 1. pointer = variable used to hold the memory address of another variable lvalue = any expression in C that refers to a memory location, and therefore it is capable of storing a data value For example: int i, *iptr; Both i and iptr are lvalues (you can store an int in i, and an address in iptr). iptr is a pointer-to-int. 2. Most important uses for pointers: - allow you to refer to large data structures in a compact way - facilitate sharing of data between different parts of a program (e.g., using pass by reference with functions) - make dynamic memory allocation possible - can be used to record relationships among data items (e.g., linked-lists and binary trees) 3. bool *flagp; 4. p1 is pointer-to-double p2 is just a double 5. Pointer assignment sets a pointer to point to something. Value assignment uses a pointer to set a value at the location the pointer is pointing to. For example: int i=0, *iptr; iptr = &i; <- pointer assignment *iptr = 100; <- value assignment 10. Bad things (program will probably crash with a Segmentation Fault). 11. Call by reference refers to the ability to give a function a reference to a variable, and then use that reference in the function to change the variable. In C we do this by sending the address of the variable to the function. In the call ConvertTimeToHM(time, &hours, &minutes), the hours and minutes variables are being passed to the function by reference. 12. ApplySpecialOperation(&x, y); only the variable x can be changed by this call 13. Use call by reference when it makes sense for the function to "return" more than one value. 16. Address of doubleArray[0] is 1000, so the address of doubleArray+5 is 1040 if doubles require 8 bytes. 19. FALSE. Well, TRUE if p is pointing to an array of 1-byte chars. However, if p is pointing to an array of 4-byte ints, then p++ would increment it by 4. If 8-byte doubles, then increment by 8, etc. 22. The heap is a part of a process' memory space that can be dynamically allocated and freed as the program runs. A process' memory space is divided into several parts. For example, there is one part for the call stack, one part contains the program's machine code instructions, and one part is the heap. 23. malloc goes out and grabs a block of memory for my program, and returns a pointer to that block. 24. void * is a general type that can by used for storage of pointer values of any type (e.g., int *, double *, char *). 25. bool *flags; flags = (bool *) malloc(100*sizeof(bool)); if (flags == NULL) { Error("No memory available..."); } 26. arr = GetBlock(10 * sizeof(int)); does the malloc plus the error checking. (Since we are using the standard C way to dynamically allocate memory (using malloc), you do not need to know what GetBlock does) 27. The "free" function returns to the heap the memory "pointed to" by its argument that was previously dynamically allocated by the program.