home *** CD-ROM | disk | FTP | other *** search
/ BURKS 2 / BURKS_AUG97.ISO / BURKS / LANGUAGE / C / PTRTUT / CH2X.HTM < prev    next >
Text File  |  1997-07-19  |  10KB  |  306 lines

  1. <H2>CHAPTER 2: Pointer types and Arrays</H2>
  2.  
  3.  
  4.  
  5.     Okay, let's move on.  Let us consider why we need to identify
  6. the <B><I>type</I></B> of variable that a pointer points to, as in:
  7.  
  8. <PRE>
  9.     int *ptr;
  10. </PRE>
  11.  
  12.     One reason for doing this is so that later, once ptr "points
  13. to" something, if we write:
  14.  
  15. <PRE>
  16.     *ptr = 2;
  17. </PRE>
  18.  
  19. the compiler will know how many bytes to copy into that memory
  20. location pointed to by <B>ptr</B>.  If <B>ptr</B> was declared as pointing to an
  21. integer, 2 bytes would be copied, if a long, 4 bytes would be
  22. copied.  Similarly for floats and doubles the appropriate number
  23. will be copied.  But, defining the type that the pointer points
  24. to permits a number of other interesting ways a compiler can
  25. interpret code.  For example, consider a block in memory
  26. consisting if ten integers in a row.  That is, 20 bytes of memory
  27. are set aside to hold 10 integers.
  28.  
  29. <P>
  30.  
  31.     Now, let's say we point our integer pointer <B>ptr</B> at the first
  32. of these integers.  Furthermore lets say that integer is located
  33. at memory location 100 (decimal).  What happens when we write:
  34.  
  35. <PRE>
  36.     ptr + 1;
  37. </PRE>
  38.  
  39.     Because the compiler "knows" this is a pointer (i.e. its
  40. value is an address) and that it points to an integer (its
  41. current address, 100, is the address of an integer), it adds 2 to
  42. <B>ptr</B> instead of 1, so the pointer "points to" the <B>next</B>
  43. <B>integer</B>, at memory location 102.  Similarly, were the <B>ptr</B>
  44. declared as a pointer to a long, it would add 4 to it instead of
  45.  
  46. 1.  The same goes for other data types such as floats, doubles,
  47. or even user defined data types such as structures.  This is
  48. obviously not the same kind of "addition" that we normally think
  49. of.  In C it is referred to as addition using "pointer
  50. arithmetic", a term which we will come back to later.
  51.  
  52. <P>
  53.  
  54.     Similarly, since <B>++ptr</B> and <B>ptr++</B> are both equivalent to
  55. <B>ptr + 1</B> (though the point in the program when <B>ptr</B> is incremented
  56. may be different), incrementing a pointer using the unary ++
  57. operator, either pre- or post-, increments the address it stores
  58. by the amount sizeof(type) where "type" is the type of the object
  59. pointed to. (i.e. 2 for an integer, 4 for a long,
  60. etc.).
  61.  
  62. <P>
  63.  
  64.     Since a block of 10 integers located contiguously in memory
  65. is, by definition, an array of integers, this brings up an
  66. interesting relationship between arrays and pointers.
  67.  
  68. <P>
  69.     Consider the following:
  70. <PRE>
  71.     int my_array[] = {1,23,17,4,-5,100};
  72. </PRE>
  73.  
  74.     Here we have an array containing 6 integers.  We refer to
  75. each of these integers by means of a subscript to <B>my_array</B>, i.e.
  76. using <B>my_array[0]</B> through <B>my_array[5]</B>.  But, we could
  77. alternatively access them via a pointer as follows:
  78.  
  79. <PRE>
  80.     int *ptr;
  81.     ptr = &my_array[0];       /* point our pointer at the first
  82.                                  integer in our array */
  83. </PRE>
  84.  
  85.     And then we could print out our array either using the array
  86. notation or by dereferencing our pointer.  The following code
  87. illustrates this:
  88.  
  89. <PRE>
  90.  
  91. -----------  Program 2.1  -----------------------------------
  92.  
  93. /* Program 2.1 from PTRTUT10.HTM   6/13/97 */
  94.  
  95.  
  96.  
  97. #include <stdio.h>
  98.  
  99. int my_array[] = {1,23,17,4,-5,100};
  100. int *ptr;
  101.  
  102. int main(void)
  103. {
  104.     int i;
  105.     ptr = &my_array[0];     /* point our pointer to the first
  106.                                       element of the array */
  107.     printf("\n\n");
  108.     for (i = 0; i < 6; i++)
  109.     {
  110.       printf("my_array[%d] = %d   ",i,my_array[i]);   /*<-- A */
  111.       printf("ptr + %d = %d\n",i, *(ptr + i));        /*<-- B */
  112.     }
  113.  
  114.     return 0;
  115. }
  116. </PRE>
  117.    Compile and run the above program and carefully note lines A
  118. and B and that the program prints out the same values in either
  119. case.  Also observe how we dereferenced our pointer in line B,
  120. i.e. we first added i to it and then dereferenced the new
  121. pointer. Change line B to read:
  122. <PRE>
  123.     printf("ptr + %d = %d\n",i, *ptr++);
  124. </PRE>
  125.  
  126. and run it again... then change it to:
  127.  
  128. <PRE>
  129.     printf("ptr + %d = %d\n",i, *(++ptr));
  130. </PRE>
  131.  
  132. and try once more.  Each time try and predict the outcome and
  133. carefully look at the actual outcome.
  134.  
  135. <P>
  136.     In C, the standard states that wherever we might use
  137. <B>&var_name[0]</B> we can replace that with <B>var_name</B>, thus in our code
  138. where we wrote:
  139.  
  140. <PRE>
  141.     ptr = &my_array[0];
  142. </PRE>
  143.  
  144.     we can write:
  145.  
  146. <PRE>
  147.     ptr = my_array;
  148. </PRE>
  149.  
  150. to achieve the same result.
  151.  
  152. <P>
  153.  
  154.     This leads many texts to state that the name of an array is a
  155. pointer.  I prefer to mentally think "the
  156. name of the array is the address of first element in the array".
  157.  
  158. Many beginners (including myself when I was learning) have a
  159. tendency to become confused by thinking of it as a pointer.
  160. For example, while we can write
  161.  
  162. <PRE>
  163.     ptr = my_array;
  164. </PRE>
  165.  
  166. we cannot write
  167.  
  168. <PRE>
  169.     my_array = ptr;
  170. </PRE>
  171.  
  172.     The reason is that the while <B>ptr</B> is a variable, <B>my_array</B> is a
  173. constant.  That is, the location at which the first element of
  174. <B>my_array</B> will be stored cannot be changed once <B>my_array[]</B> has
  175. been declared.
  176.  
  177. <P>
  178.     Earlier when discussing the term "lvalue" I cited K&R-2 where
  179. it stated:
  180.  
  181. <BLOCKQUOTE>
  182.  
  183.     "An <B>object</B> is a named region of storage; an <B>lvalue</B> is an
  184.      expression referring to an object".
  185.  
  186. </BLOCKQUOTE>
  187.  
  188. This raises an interesting problem.  Since <B>my_array</B> is a named
  189. region of storage, why is <B>my_array</B> in the above assignment
  190. statement not an lvalue?  To resolve this problem, some refer to
  191. <B>my_array</B> as an "unmodifiable lvalue".
  192.  
  193. <P>
  194.  
  195. Modify the example program above by changing
  196.  
  197. <PRE>
  198.     ptr = &my_array[0];
  199. </PRE>
  200. to
  201. <PRE>
  202.     ptr = my_array;
  203. </PRE>
  204.  
  205. and run it again to verify the results are identical.
  206.  
  207. <P>
  208.  
  209.     Now, let's delve a little further into the difference between
  210. the names <B>ptr</B> and <B>my_array</B> as used above.  Some writers will
  211. refer to an array's name as a <B><I>constant</I></B> pointer.  What do we
  212. mean by that?  Well, to understand the term "constant" in this
  213. sense, let's go back to our definition of the term "variable".
  214. When we declare a variable we set aside a spot in memory to hold
  215. the value of the appropriate type.  Once that is done the name of
  216. the variable can be interpreted in one of two ways.  When used on
  217. the left side of the assignment operator, the compiler interprets
  218. it as the memory location to which to move that value resulting
  219. from evaluation of the right side of the assignment operator.
  220. But, when used on the right side of the assignment operator, the
  221. name of a variable is interpreted to mean the contents stored at
  222. that memory address set aside to hold the value of that variable.
  223.  
  224. <P>
  225.  
  226.     With that in mind, let's now consider the simplest of
  227. constants, as in:
  228.  
  229. <PRE>
  230.     int i, k;
  231.     i = 2;
  232. </PRE>
  233.  
  234.     Here, while <B>i</B> is a variable and then occupies space in the
  235. data portion of memory, <B>2</B> is a constant and, as such, instead
  236. of setting aside memory in the data segment, it is imbedded
  237. directly in the code segment of memory.  That is, while writing
  238. something like <B>k = i;</B>  tells the compiler to create code which at
  239. run time will look at memory location <B>&i</B> to determine the value
  240. to be moved to <B>k</B>, code created by <B> i = 2;</B>  simply puts the <B>2</B> in
  241. the code and there is no referencing of the data segment.  That
  242. is, both <B>k</B> and <B>i</B> are objects, but <B>2</B> is not an object.
  243.  
  244. <P>
  245.  
  246.     Similarly, in the above, since <B>my_array</B> is a constant, once
  247. the compiler establishes where the array itself is to be stored,
  248. it "knows" the address of <B>my_array[0]</B> and on seeing:
  249.  
  250. <PRE>
  251.     ptr = my_array;
  252. </PRE>
  253.  
  254. it simply uses this address as a constant in the code segment and
  255. there is no ref