home *** CD-ROM | disk | FTP | other *** search
/ Shareware Overload / ShartewareOverload.cdr / progm / ctutor1.zip / CHAP08.TXT < prev    next >
Text File  |  1989-11-10  |  21KB  |  469 lines

  1.  
  2.  
  3.  
  4.  
  5.                                                     Chapter 8
  6.                                                      POINTERS
  7.  
  8.  
  9.  
  10. WHAT IS A POINTER?
  11. ____________________________________________________________
  12.  
  13. Simply stated, a pointer is an address.         =============
  14. Instead of being a variable, it is a pointer      POINTER.C
  15. to a variable stored somewhere in the address   =============
  16. space of the program.  It is always best to
  17. use an example so load the file named
  18. POINTER.C and display it on your monitor for an example of a
  19. program with some pointers in it.
  20.  
  21. For the moment, ignore the data declaration statement where
  22. we define index and two other fields beginning with a star. 
  23. It is properly called an asterisk, but for reasons we will see
  24. later, let's agree to call it a star.  If you observe the
  25. first statement, it should be clear that we assign the value
  26. of 39 to the variable named index.  This is no surprise, we
  27. have been doing it for several programs now.  The statement
  28. in line 9 however, says to assign to pt1 a strange looking
  29. value, namely the variable index with an ampersand in front
  30. of it.  In this example, pt1 and pt2 are pointers, and the
  31. variable named index is a simple variable.  Now we have a
  32. problem.  We need to learn how to use pointers in a program,
  33. but to do so requires that first we define the means of using
  34. the pointers in the program.
  35.  
  36. The following two rules will be somewhat confusing to you at
  37. first but we need to state the definitions before we can use
  38. them.  Take your time, and the whole thing will clear up very
  39. quickly.
  40.  
  41.  
  42.  
  43. TWO VERY IMPORTANT RULES
  44. ____________________________________________________________
  45.  
  46. The following two rules are very important when using pointers
  47. and must be thoroughly understood.
  48.  
  49. 1.   A variable name with an ampersand in front of it defines
  50.      the address of the variable and therefore points to the
  51.      variable.  You can therefore read line nine as "pt1 is
  52.      assigned the value of the address of index". 
  53.  
  54. 2.   A pointer with a star in front of it refers to the value
  55.      of the variable pointed to by the pointer.  Line twelve
  56.      of the program can be read as "The stored (starred) value
  57.      to which the pointer pt1 points is assigned the value
  58.  
  59.                                                      Page 8-1
  60.  
  61.                                          Chapter 8 - Pointers
  62.  
  63.      13".  Now you can see why it is convenient to think of
  64.      the asterisk as a star,  it sort of sounds like the word
  65.      store.
  66.  
  67.  
  68. MEMORY AIDS
  69. ____________________________________________________________
  70.  
  71. 1. Think of & as an address.
  72. 2. Think of * as a star referring to stored.
  73.  
  74. Assume for the moment that pt1 and pt2 are pointers (we will
  75. see how to define them shortly).  As pointers, they do not
  76. contain a variable value but an address of a variable and can
  77. be used to point to a variable.  Figure 8-1 is a graphical
  78. representation of the data space as it is configured at this
  79. time.  A box represents a variable, and a box with a dot in
  80. it represents a pointer.  At this time the pointers are not
  81. pointing at anything, so they have no arrows emanating from
  82. the boxes.
  83.  
  84. Continuing execution of the program, we come to line 9 which
  85. assigns the pointer pt1 to point to the variable we have
  86. already defined as index because we have assigned the address
  87. of index to pt1.  Since we have a pointer to index, we can
  88. manipulate the value of index by using either the variable
  89. name itself, or the pointer.  Figure 8-2 depicts the condition
  90. of the data space after executing line 9.
  91.  
  92.  
  93. Line 12 modifies the value by using the pointer.  Since the
  94. pointer pt1 points to the variable named index, then putting
  95. a star in front of the pointer name refers to the memory
  96. location to which it is pointing.  Line 12 therefore assigns
  97. to index the value of 13.  Anyplace in the program where it
  98. is permissible to use the variable name index, it is also
  99. permissible to use the name *pt1 since they are identical in
  100. meaning until the pointer is reassigned to some other
  101. variable.
  102.  
  103.  
  104. ANOTHER POINTER
  105. ____________________________________________________________
  106.  
  107. Just to add a little intrigue to the system, we have another
  108. pointer defined in this program, pt2.  Since pt2 has not been
  109. assigned a value prior to statement 10, it doesn't point to
  110. anything, it contains garbage.  Of course, that is also true
  111. of any variable until a value is assigned to it.  The
  112. statement in line 10 assigns pt2 the same address as pt1, so
  113. that now pt2 also points to the variable named index.  So to
  114. continue the definition from the last paragraph, anyplace in
  115. the program where it is permissible to use the variable index,
  116. it is also permissible to use the name *pt2 because they  are
  117.  
  118.                                                      Page 8-2
  119.  
  120.                                          Chapter 8 - Pointers
  121.  
  122. identical in meaning.  This fact is illustrated in the
  123. printf() statement in line 11 since this statement uses the
  124. three means of identifying the same variable to print out the
  125. same variable three times.  Refer to figure 8-3 for the
  126. representation of the data space at this time.
  127.  
  128.  
  129. THERE IS ONLY ONE VARIABLE
  130. ____________________________________________________________
  131.  
  132. Note carefully that, even though it appears that there are
  133. three variables, there is really only one variable.  The two
  134. pointers point to the single variable.  This is illustrated
  135. in the next statement which assigns the value of 13 to the
  136. variable index, because that is where the pointer pt1 is
  137. pointing.  The printf() statement in line 13 causes the new
  138. value of 13 to be printed out three times.  Keep in mind that
  139. there is really only one variable to be changed, not three. 
  140. Figure 8-4 is the graphical representation of the data space
  141. at this point.
  142.  
  143. This is admittedly a very difficult concept, but since it is
  144. used extensively in all but the most trivial C programs, it
  145. is well worth your time to stay with this material until you
  146. understand it thoroughly.
  147.  
  148.  
  149. HOW DO YOU DECLARE A POINTER?
  150. ____________________________________________________________
  151.  
  152. Now to keep a promise and tell you how to define a pointer. 
  153. Refer to line 6 of the program and you will see our old
  154. familiar way of defining the variable index, followed by two
  155. more definitions.  The second definition can be read as "the
  156. storage location to which pt1 points will be an int type
  157. variable".  Therefore, pt1 is a pointer to an int type
  158. variable.  Likewise, pt2 is another pointer to an int type
  159. variable, because it has a star (asterisk) in front of it.
  160.  
  161. A pointer must be defined to point to a specific type of
  162. variable.  Following a proper definition, it cannot be used
  163. to point to any other type of variable or it will result in
  164. a type incompatibility error.  In the same manner that a float
  165. type of variable cannot be added to an int type variable, a
  166. pointer to a float variable cannot be used to point to an
  167. integer variable without a little extra trouble.
  168.  
  169. Compile and run this program and observe that there is only
  170. one variable and the single statement in line 12 changes the
  171. one variable which is displayed three times.  This material
  172. is so important that you should review it carefully if you do
  173. not fully understand it at this time.
  174.  
  175.  
  176.  
  177.                                                      Page 8-3
  178.  
  179.                                          Chapter 8 - Pointers
  180.  
  181. THE SECOND PROGRAM WITH POINTERS
  182. ____________________________________________________________
  183.  
  184. In these few pages so far on pointers, we      ==============
  185. have covered a lot of territory, but it is       POINTER2.C
  186. important territory.  We still have a lot of   ==============
  187. material to cover so stay in tune as we
  188. continue this important aspect of C.  Load
  189. the next file named POINTER2.C and display it on your monitor
  190. so we can continue our study.
  191.  
  192. In this program we have defined several variables and two
  193. pointers.  The first pointer named there is a pointer to a
  194. char type variable and the second named pt points to an int
  195. type variable.  Notice also that we have defined two array
  196. variables named strg and list.  We will use them to show the
  197. correspondence between pointers and array names.
  198.  
  199. Figure 8-5 depicts the data space at this time.  There are
  200. three variables, two pointers, and two strings.  Each string
  201. is composed of the string itself and a pointer which points
  202. to the beginning of the string.  This will be completely
  203. defined in the next paragraph.  The string itself is composed
  204. of a number of identical elements of which only a few at the
  205. beginning and a few at the end are depicted graphically.
  206.  
  207.  
  208. A STRING VARIABLE IS ACTUALLY A POINTER
  209. ____________________________________________________________
  210.  
  211. In the programming language C, a string variable is defined
  212. to be simply a pointer to the beginning of a string.  This
  213. will take some explaining.  Refer to the example program on
  214. your monitor.  You will notice that in line 10 we assign a
  215. string constant to the string variable named strg so we will
  216. have some data to work with.  Next, we assign the value of the
  217. first element to the variable one, a simple char variable. 
  218. Next, since the string name is a pointer by definition of the
  219. C language, we can assign the same value to two by using the
  220. star and the string name.  The result of the two assignments
  221. are such that one now has the same value as two, and both
  222. contain the character T, the first character in the string. 
  223. Note that it would be incorrect to write line 10 as two =
  224. *strg[0]; because the star takes the place of the square
  225. brackets.
  226.  
  227. For all practical purposes, strg is a pointer.  It does,
  228. however, have one restriction that a true pointer does not
  229. have.  It cannot be changed like a variable, but must always
  230. contain the initial value and therefore always points to its
  231. string.  It could be thought of as a pointer constant, and in
  232. some applications you may desire a pointer that cannot be
  233. corrupted in any way.  Even though it cannot be changed, it
  234. can be used to refer to other values than the one it is
  235.  
  236.                                                      Page 8-4
  237.  
  238.                                          Chapter 8 - Pointers
  239.  
  240. defined to point to, as we will see in the next section of the
  241. program.
  242.  
  243. Moving ahead to line 16, the variable one is assigned the
  244. value of the ninth variable (since the indexing starts at
  245. zero) and two is assigned the same value because we are
  246. allowed to index a pointer to get to values farther ahead in
  247. the string.  Both variables now contain the character a.
  248.  
  249.  
  250.  
  251. POINTER INDEXING
  252. ____________________________________________________________
  253.  
  254. The C programming language takes care of indexing for us
  255. automatically by adjusting the indexing for the type of
  256. variable the pointer is pointing to.  In this case, the index
  257. of 8 is simply added to the pointer value before looking up
  258. the desired result because a char type variable is one byte
  259. long.  If we were using a pointer to an int type variable, the
  260. index would be doubled and added to the pointer before looking
  261. up the value because an int type variable uses two bytes per
  262. value stored on most microcomputers.  When we get to the
  263. chapter on structures, we will see that a variable can have
  264. many, even into the hundreds or thousands, of bytes per
  265. variable, but the indexing will be handled automatically for
  266. us by the system.
  267.  
  268. The data space is now in the condition defined graphically in
  269. figure 8-6.  The string named strg has been filled and the two
  270. variables named one and two have the letter a stored in them. 
  271. Since there is already a pointer, it can be assigned the
  272. address of the 11th element of strg by the statement in line
  273. 20 of this program.  Remember that since there is a pointer
  274. to type char, it can be assigned any value as long as that
  275. value represents a char type of address.  It should be clear
  276. that the pointers must be typed in order to allow the pointer
  277. arithmetic described in the last paragraph to be done
  278. properly.  The third and fourth outputs will be the same,
  279. namely the letter c.
  280.  
  281.  
  282.  
  283. POINTER ARITHMETIC
  284. ____________________________________________________________
  285.  
  286. Not all forms of arithmetic are permissible on a pointer. 
  287. Only those things that make sense, considering that a pointer
  288. is an address somewhere in the computer.  It would make sense
  289. to add a constant to an address, thereby moving it ahead in
  290. memory that number of places.  Likewise, subtraction is
  291. permissible, moving it back some number of locations.  Adding
  292. two pointers together would not make sense because absolute
  293. memory addresses are not additive.  Pointer multiplication is
  294.  
  295.                                                      Page 8-5
  296.  
  297.                                          Chapter 8 - Pointers
  298.  
  299. also not allowed, as that would be a funny number.  If you
  300. think about what you are actually doing, it will make sense
  301. to you what is allowed, and what is not.
  302.  
  303.  
  304. NOW FOR AN INTEGER POINTER
  305. ____________________________________________________________
  306.  
  307. The array named list is assigned a series of values from 100
  308. to 199 in order to have some data to work with in lines 24 and
  309. 25.  Next we assign the pointer pt the address of the 28th
  310. element of the list and print out the same value both ways to
  311. illustrate that the system truly will adjust the index for the
  312. int type variable.  You should spend some time in this program
  313. until you feel you fairly well understand these lessons on
  314. pointers.
  315.  
  316. Compile and execute POINTER2.C and study the output.  At the
  317. termination of execution, the data space will be as depicted
  318. in figure 8-7.
  319.  
  320.  
  321. FUNCTION DATA RETURN WITH A POINTER
  322. ____________________________________________________________
  323.  
  324. You may recall that back in the lesson on func-  ============
  325. tions we mentioned that there were two ways to     TWOWAY.C
  326. get variable data back from a function.  One way ============
  327. is through use of the array, and you should be
  328. right on the verge of guessing the other way.  If
  329. your guess is through use of a pointer, you are correct.  Load
  330. and display the example program named TWOWAY.C for an example
  331. of this.
  332.  
  333. In TWOWAY.C, there are two variables defined in the main
  334. program, pecans and apples.  Notice that neither of these is
  335. defined as a pointer.  We assign values to both of these and
  336. print them out, then call the function named fixup() taking
  337. with us both of these values.  The variable pecans is simply
  338. sent to the function, but the address of the variable apples
  339. is sent to the function.  Now we have a problem.  The two
  340. arguments are not the same, the second is a pointer to a
  341. variable.  We must somehow alert the function to the fact that
  342. it is supposed to receive an integer variable and a pointer
  343. to an integer variable.  This turns out to be very simple. 
  344. Notice that the parameter definitions in line 20 defines nuts
  345. as an integer, and fruit as a pointer to an integer.  The call
  346. in the main program therefore is now in agreement with the
  347. function heading and the program interface will work just
  348. fine.
  349.  
  350. In the body of the function, we print the two values sent to
  351. the function, then modify them and print the new values out. 
  352. This should be perfectly clear to you by now.  The surprise
  353.  
  354.                                                      Page 8-6
  355.  
  356.                                          Chapter 8 - Pointers
  357.  
  358. occurs when we return to the main program and print out the
  359. two values again.  We will find that the value of pecans will
  360. be restored to its value before the function call because the
  361. C language makes a copy of the item in question and takes the
  362. copy to the called function, leaving the original intact.  In
  363. the case of the variable apples, we made a copy of a pointer
  364. to the variable and took the copy of the pointer to the
  365. function.  Since we had a pointer to the original variable,
  366. even though the pointer was a local copy, we had access to the
  367. original variable and could change it in the function.  When
  368. we returned to the main program, we found a changed value in
  369. apples when we printed it out. 
  370.  
  371. This is illustrated graphically in figure 8-8.  The state of
  372. the system is illustrated following execution of line 25 of
  373. the program.
  374.  
  375. By using a pointer in a function call, we can have access to
  376. the data in the function and change it in such a way that when
  377. we return to the calling program, we have a changed value of
  378. the original variable.  It must be pointed out however, that
  379. if you modify the value of the pointer itself in the function,
  380. you will have a restored pointer when you return because the
  381. pointer you use in the function is a copy of the original. 
  382. In this example, there was no pointer in the main program
  383. because we simply sent the address to the function, but in
  384. many programs you will use pointers in function calls.  One
  385. of the places you will find need for pointers in function
  386. calls will be when you request data input using standard
  387. input/output routines.  These will be covered in the next two
  388. chapters.  Compile and run TWOWAY.C and observe the output.
  389.  
  390.  
  391. POINTERS ARE VALUABLE
  392. ____________________________________________________________
  393.  
  394. Even though you are probably somewhat intimidated at this
  395. point by the use of pointers, you will find that after you
  396. gain experience, you will use them profusely in many ways. 
  397. You will also use pointers in every program you write other
  398. than the most trivial because they are so useful.  You should
  399. probably go over this material carefully several times until
  400. you feel comfortable with it because it is very important in
  401. the area of input/output which is next on the agenda.
  402.  
  403.  
  404. A POINTER TO A FUNCTION
  405. ____________________________________________________________
  406.  
  407. Examine the example program named FUNCPNT.C     =============
  408. for the most unusual pointer yet.  This           FUNCPNT.C
  409. program contains a pointer to a function, and   =============
  410. illustrates how to use it.
  411.  
  412.  
  413.                                                      Page 8-7
  414.  
  415.                                          Chapter 8 - Pointers
  416.  
  417. Line 8 of this program defines function_pointer as a pointer
  418. to a function and not to just any function, it points to a
  419. function with a single formal parameter of type float.  The
  420. function must also return nothing because of the void before
  421. the pointer definition.  The parentheses are required around
  422. the pointer name as illustrated or the system will think it
  423. is a prototype definition for a function that returns a
  424. pointer to void.
  425.  
  426. You will note the prototypes given in lines 4 through 6 that
  427. declare three functions that use the same parameter and return
  428. type as the pointer.  Since they are the same as the pointer,
  429. the pointer can be used to refer to them as is illustrated in
  430. the executable part of the program.  Line 15 contains a call
  431. to the print_stuff() function, and line 16 assigns the value
  432. of print_stuff to function_pointer.  Because the name of a
  433. function is defined as a pointer to that function, its name
  434. can be assigned to a function pointer variable.  You will
  435. recall that the name of an array is actually a pointer
  436. constant to the first element of the array.  In like manner,
  437. a function name is actually a pointer constant which is
  438. pointing to the function itself.
  439.  
  440. A function pointer can be passed to another function as a
  441. parameter and can be used within the function to call the
  442. function which is pointed to.  You are not permitted to
  443. increment or add a constant to a function pointer, it can only
  444. be assigned the value of a function with the same parameters
  445. and return with which it was initially declared.
  446.  
  447. If you continue your study of this program, you will see that
  448. the function pointer is used to refer to all three functions
  449. in various ways.
  450.  
  451.  
  452. PROGRAMMING EXERCISES
  453. ____________________________________________________________
  454.  
  455. 1.   Define a character array and use strcpy() to copy a
  456.      string into it.  Print the string out by using a loop
  457.      with a pointer to print out one character at a time.
  458.      Initialize the pointer to the first element and use the
  459.      double plus sign to increment the pointer. Use a separate
  460.      integer variable to count the characters to print.
  461.  
  462. 2.   Modify the program from programming exercise 1 to print
  463.      out the string backwards by pointing to the end and using
  464.      a decrementing pointer.
  465.  
  466.  
  467.  
  468.                                                      Page 8-8
  469.