home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / c / tutorial / cpptutor / text / chap03.txt < prev    next >
Encoding:
Text File  |  1994-05-15  |  14.1 KB  |  290 lines

  1.  
  2.  
  3.  
  4.                                                         Chapter 3
  5.                                                          POINTERS
  6.  
  7. Because pointers are so important in C and C++, this chapter will 
  8. review some of the more important topics concerning pointers.  
  9. Even if you are extremely conversant in the use of pointers, you 
  10. should not completely ignore this chapter because some new 
  11. material unique to C++ is presented here.
  12.  
  13.  
  14. POINTER REVIEW
  15. -----------------------------------------------------------------
  16. Examine the program named POINTERS.CPP for a   ==================
  17. simple example of the use of pointers.  This      POINTERS.CPP
  18. is a pointer review and if you are             ==================
  19. comfortable with the use of pointers, you can 
  20. skip this example program completely. A pointer in either ANSI-C 
  21. or C++ is declared with an asterisk preceding the variable name.  
  22. The pointer is then a pointer to a variable of that one specific 
  23. type and should not be used with variables of other types.  Thus 
  24. pt_int is a pointer to an integer type variable and should not be 
  25. used with any other type.  Of course, an experienced C programmer 
  26. knows that it is simple to coerce the pointer to be used with 
  27. some other type by using a cast, but he must then assume the 
  28. responsibility for its correct usage.
  29.  
  30. In line 12 the pointer named pt_int is assigned the address of 
  31. the variable named pig and line 13 uses the pointer named pt_int 
  32. to add the value of dog to the value of pig because the asterisk 
  33. dereferences the pointer in exactly the same manner as standard 
  34. C.  The address is used to print out the value of the variable 
  35. pig in line 14 illustrating the use of a pointer with the stream 
  36. output operator cout.  Likewise, the pointer to float named 
  37. pt_float is assigned the address of x, then used in a trivial 
  38. calculation in line 18.  Figure 3-1 is a graphical representation 
  39. of the data space following execution of line 13.  Note that a 
  40. box containing a dot represents a pointer.
  41.  
  42. If you are not completely comfortable with this trivial program 
  43. using pointers, you should review the use of pointers in any good 
  44. C programming book or Coronado Enterprises C tutorial before 
  45. proceeding on because we will assume that you have a thorough 
  46. knowledge of pointers throughout the remainder of this tutorial.  
  47. It is not possible to write a C program of any significant size 
  48. or complexity without the use of pointers.
  49.  
  50.  
  51. CONSTANT POINTERS AND POINTERS TO CONSTANTS
  52. -----------------------------------------------------------------
  53. The definition of C++ allows a pointer to a constant to be 
  54. defined such that the value to which the pointer points cannot be 
  55. changed but the pointer itself can be moved to another variable 
  56.  
  57.                                                          Page 3-1
  58.  
  59.                                              Chapter 3 - Pointers
  60.  
  61. or constant.  The method of defining a pointer to a constant is 
  62. illustrated in line 22.  In addition to a pointer to a constant, 
  63. you can also declare a constant pointer, one that cannot be 
  64. changed.  Line 23 illustrates this.  Note that neither of these 
  65. pointers are used in illustrative code.
  66.  
  67. Either of these constructs can be used to provide additional 
  68. compile time checking and improve the quality of your code.  If 
  69. you know a pointer will never be moved due to its nature, you 
  70. should define it as a constant pointer.  If you know that a value 
  71. will not be changed, it can be defined as a constant and the 
  72. compiler will tell you if you ever inadvertently attempt to 
  73. change it.
  74.  
  75.  
  76. A POINTER TO VOID
  77. -----------------------------------------------------------------
  78. The pointer to void is actually a part of the ANSI-C standard but 
  79. is relatively new so it is commented upon here.  A pointer to 
  80. void can be assigned the value of any other pointer type.  You 
  81. will notice that the pointer to void named general is assigned an 
  82. address of an int type in line 15 and the address of a float type 
  83. in line 20 with no cast and no complaints from the compiler.  
  84. This is a relatively new concept in C and C++.  It allows a 
  85. programmer to define a pointer that can be used to point to many 
  86. different kinds of things to transfer information around within a 
  87. program.  A good example is the malloc() function which returns a 
  88. pointer to void.  This pointer can be assigned to point to any 
  89. entity, thus transferring the returned pointer to the correct 
  90. type.
  91.  
  92. A pointer to void is aligned in memory in such a way that it can 
  93. be used with any of the simple predefined types available in C++, 
  94. or in ANSI-C for that matter.  They will also align with any 
  95. compound types the user can define since compound types are 
  96. composed of the simpler types.
  97.  
  98. Be sure to compile and execute this program.
  99.  
  100.  
  101. DYNAMIC ALLOCATION AND DEALLOCATION
  102. -----------------------------------------------------------------
  103. Examine the program named NEWDEL.CPP for our   ==================
  104. first example of the new and delete operators.     NEWDEL.CPP
  105. The new and delete operators do dynamic        ==================
  106. allocation and deallocation in much the same 
  107. manner that malloc() and free() do in your old favorite C 
  108. implementation.
  109.  
  110. During the design of C++, it was felt that since dynamic 
  111. allocation and deallocation are such a heavily used part of the C 
  112. programming language and would also be heavily used in C++, it 
  113. should be a part of the language, rather than a library add-on.  
  114.  
  115.                                                          Page 3-2
  116.  
  117.                                              Chapter 3 - Pointers
  118.  
  119. The new and delete operators are actually a part of the C++ 
  120. language and are operators, much like the addition operator or 
  121. the assignment operator.  They are therefore very efficient, and 
  122. are very easy to use as we will see in this example program.
  123.  
  124. Lines 14 and 15 illustrate the use of pointers in the tradition 
  125. of C and line 16 illustrates the use of the new operator.  This 
  126. operator requires one modifier which must be a type as 
  127. illustrated here.  The pointer named point2 is now pointing at 
  128. the dynamically allocated integer variable which exists on the 
  129. heap, and can be used in the same way that any dynamically 
  130. allocated variable is used in ANSI-C.  Line 18 illustrates 
  131. displaying the value on the monitor which was assigned in line 
  132. 17.
  133.  
  134. Line 20 allocates another new variable and line 21 causes point2 
  135. to refer to the same dynamically allocated variable as point1 is 
  136. pointing to.  In this case, the reference to the variable that 
  137. point2 was previously pointing to has been lost and it can never 
  138. be used or deallocated.  It is lost on the heap until we return 
  139. to the operating system when it will be reclaimed for further 
  140. use, so this is obviously not good practice.  Note that point1 is 
  141. deallocated with the delete operator in line 25, and point2 can 
  142. not be deleted since it is now pointing to nothing.  Since the 
  143. pointer point1 itself is not changed, it is actually still 
  144. pointing to the original data on the heap.  This data could 
  145. probably be referred to again using point1, but it would be 
  146. terrible programming practice since you have no guarantee what 
  147. the system will do with the pointer or the data.  The data 
  148. storage is returned to the free list to be allocated in a 
  149. subsequent call, and will soon be reused in any practical 
  150. program.
  151.  
  152. Since the delete operator is defined to do nothing if it is 
  153. passed a NULL value, it is legal to ask the system to delete the 
  154. data pointed to by a pointer with the value of NULL, but nothing 
  155. will actually happen.  It is actually wasted code.  The delete 
  156. operator can only be used to delete data allocated by a new 
  157. operator.  If the delete is used with any other kind of data, the 
  158. operation is undefined and anything can happen.  According to the 
  159. ANSI standard, even a system crash is a legal result of this 
  160. illegal operation, and can be defined as such by the compiler 
  161. writer.
  162.  
  163. In line 27, we declare some floating point variables.  You will 
  164. remember that in C++ the variables do not have to be declared at 
  165. the beginning of a block.  A declaration is an executable 
  166. statement and can therefore appear anywhere in a list of 
  167. executable statements.  One of the float variables is allocated 
  168. within the declaration to illustrate that this can be done.  Some 
  169. of the same operations are performed on these float type 
  170. variables as were done on the int types earlier.
  171.  
  172.  
  173.                                                          Page 3-3
  174.  
  175.                                              Chapter 3 - Pointers
  176.  
  177. Some examples of the use of a structure are given in lines 35 
  178. through 41 and should be self explanatory.
  179.  
  180. Finally, since the new operator requires a type to determine the 
  181. size of the dynamically allocated block, you may wonder how you 
  182. can allocate a block of arbitrary size.  This is possible by 
  183. using the construct illustrated in line 47 where a block of 37 
  184. char sized entities, which will be 37 bytes, is allocated.  A 
  185. block of 133 bytes greater than the size of the date structure is 
  186. allocated in line 49.  It is therefore clear that the new 
  187. operator can be used with all of the flexibility of the malloc() 
  188. function which you are familiar with.  The brackets are required 
  189. in lines 48 and 50 to tell the compiler that it is deallocating 
  190. an array.
  191.  
  192. The standard functions which you have been using in C for dynamic 
  193. memory management, malloc(), calloc(), and free(), are also 
  194. available for use in C++ and can be used in the same manner they 
  195. were used in C.  The new and delete operators should not be 
  196. intermixed with the older function calls since the results may be 
  197. unpredictable.  If you are updating code with the older function 
  198. calls, continue to use them for any additions to the code.  If 
  199. you are designing and coding a new program you should use the 
  200. newer constructs because they are a built in part of the language 
  201. rather than an add on and are therefore more efficient.
  202.  
  203. Be sure to compile and execute this program.
  204.  
  205.  
  206. POINTERS TO FUNCTIONS
  207. -----------------------------------------------------------------
  208. Examine the program named FUNCPNT.CPP for an    =================
  209. example of using a pointer to a function.  It      FUNCPNT.CPP
  210. must be pointed out that there is nothing new   =================
  211. here, the pointer to a function is available 
  212. in ANSI-C as well as in C++ and works in the manner described 
  213. here for both languages.  It is not regularly used by most C 
  214. programmers, so it is briefly discussed here as a refresher.  If 
  215. you are comfortable with the use of pointers to functions, you 
  216. can skip this discussion entirely.
  217.  
  218. There is nothing unusual about this program except for the 
  219. pointer to a function declared in line 7.  This declares a 
  220. pointer to a function which returns nothing (void) and requires a 
  221. single formal parameter, a float type variable.  You will notice 
  222. that all three of the functions declared in lines 4 through 6 fit 
  223. this profile and are therefore candidates to be called with this 
  224. pointer.  If you have not used prototyping in C, these lines will 
  225. look strange to you.  Don't worry about them at this point since 
  226. we will study prototyping in the next chapter of this tutorial.
  227.  
  228. Observe that in line 14 we call the function print_stuff() with 
  229. the parameter pi and in line 15 we assign the function pointer 
  230.  
  231.                                                          Page 3-4
  232.  
  233.                                              Chapter 3 - Pointers
  234.  
  235. named function_pointer the value of print_stuff() and use the 
  236. function pointer to call the same function again in line 16.  
  237. Lines 14 and 16 are therefore identical in what is accomplished 
  238. because of the pointer assignment in line 15.  In lines 17 
  239. through 22, a few more illustrations of the use of the function 
  240. pointer are given.  You will be left to study these on your own.
  241.  
  242. Since we assigned the name of a function to a function pointer, 
  243. and did not get an assignment error, the name of a function must 
  244. be a pointer to that function.  This is exactly the case.  A 
  245. function name is a pointer to that function, but it is a pointer 
  246. constant and cannot be changed.  This is exactly the case we 
  247. found when we studied arrays in ANSI-C at some point in our C 
  248. programming background.  An array name is a pointer constant to 
  249. the first element of the array.
  250.  
  251. Since the name of the function is a constant pointer to that 
  252. function, we can assign the name of the function to a function 
  253. pointer and use the function pointer to call the function.  The 
  254. only caveat is that the return value and the number and types of 
  255. parameters must be identical.  Most C and C++ compilers will not, 
  256. and in fact, can not warn you of type mismatches between the 
  257. parameter lists when the assignments are made.  This is because 
  258. the assignments are done at runtime when no type information is 
  259. available to the system, rather than at compile time when all 
  260. type information is available.
  261.  
  262. The use and operation of pointers must be thoroughly understood 
  263. when we get to the material on dynamic binding and polymorphism 
  264. later in this tutorial.  It will be discussed in detail at that 
  265. time.
  266.  
  267. Be sure to compile and execute this program.
  268.  
  269.  
  270. PROGRAMMING EXERCISES
  271. -----------------------------------------------------------------
  272. 1.  When dynamically allocated data is deleted, it is still 
  273.     actually in memory, stored on the heap.  Repeat the output 
  274.     statement from line 23 of NEWDEL.CPP immediately following 
  275.     the delete in line 25 to see if the values are really still 
  276.     there.  Repeat it once again just prior to the end of the 
  277.     program when the data spaces should have been written over to 
  278.     see if you get garbage out.  Even if your compiler reports 
  279.     the correct data, it is terrible practice to count on this 
  280.     data still being there because in a large dynamic program, 
  281.     the heap space will be used repeatedly.
  282.  
  283. 2.  Add a function to FUNCPNT.CPP which uses a single integer for 
  284.     a parameter and attempt to call it by using the function 
  285.     pointer to see if you get the correct data into the function.
  286.  
  287.  
  288.  
  289.                                                          Page 3-5
  290.