home *** CD-ROM | disk | FTP | other *** search
/ Collection of Hack-Phreak Scene Programs / cleanhpvac.zip / cleanhpvac / PTR_HELP.ZIP / ptr_help.txt
Text File  |  1995-03-14  |  43KB  |  1,118 lines

  1.            UNDERSTANDING POINTERS (for beginners)
  2.                       by  Ted Jensen
  3.                        Version 0.0
  4.       This material is hereby placed in the public domain.
  5.                      September 5, 1993
  6.  
  7.                      TABLE OF CONTENTS
  8.  
  9.     INTRODUCTION;
  10.  
  11.     CHAPTER 1: What is a pointer?
  12.  
  13.     CHAPTER 2: Pointer types and Arrays
  14.  
  15.     CHAPTER 3: Pointers and Strings
  16.  
  17.     CHAPTER 4: More on Strings
  18.  
  19.     CHAPTER 5: Pointers and Structures
  20.  
  21.     CHAPTER 6: Some more on Strings, and Arrays of Strings
  22.  
  23.     EPILOG:
  24.  
  25. ==================================================================
  26.  
  27. INTRODUCTION:
  28.  
  29.     Over a period of several years of monitoring various
  30. telecommunication conferences on C I have noticed that one of the
  31. most difficult problems for beginners was the understanding of
  32. pointers.  After writing dozens of short messages in attempts to
  33. clear up various fuzzy aspects of dealing with pointers, I set up
  34. a series of messages arranged in "chapters" which I could draw
  35. from or email to various individuals who appeared to need help in
  36. this area.
  37.  
  38.     Recently, I posted all of this material in the FidoNet CECHO
  39. conference.  It received such a good acceptance, I decided to
  40. clean it up a little and submit it for inclusion in Bob Stout's
  41. SNIPPETS file.
  42.  
  43.     It is my hope that I can find the time to expand on this text
  44. in the future.  To that end, I am hoping that those who read this
  45. and find where it is lacking, or in error, or unclear, would
  46. notify me of same so the next version, should there be one, I can
  47. correct these deficiencys.
  48.  
  49.     It is impossible to acknowledge all those whose messages on
  50. pointers in various nets contributed to my knowledge in this
  51. area.  So, I will just say Thanks to All.
  52.  
  53.     I frequent the CECHO on FidoNet via RBBSNet and can be
  54. contacted via the echo itself or by email at:
  55.  
  56.      RBBSNet address 8:916/1.
  57.  
  58. I can also be reached via
  59.  
  60. Internet email at ted.jensen@spacebbs.com
  61.  
  62. Or     Ted Jensen
  63.        P.O. Box 324
  64.        Redwood City, CA 94064
  65.  
  66. ==================================================================
  67. CHAPTER 1: What is a pointer?
  68.  
  69.     One of the things beginners in C find most difficult to
  70. understand is the concept of pointers.  The purpose of this
  71. document is to provide an introduction to pointers and their use
  72. to these beginners.
  73.  
  74.     I have found that often the main reason beginners have a
  75. problem with pointers is that they have a weak or minimal feeling
  76. for variables, (as they are used in C).  Thus we start with a
  77. discussion of C variables in general.
  78.  
  79.     A variable in a program is something with a name, the value
  80. of which can vary.  The way the compiler and linker handles this
  81. is that it assigns a specific block of memory within the computer
  82. to hold the value of that variable.  The size of that block
  83. depends on the range over which the variable is allowed to vary.
  84. For example, on PC's the size of an integer variable is 2 bytes,
  85. and that of a long integer is 4 bytes.  In C the size of a
  86. variable type such as an integer need not be the same on all
  87. types of machines.
  88.  
  89.     When we declare a variable we inform the compiler of two
  90. things, the name of the variable and the type of the variable.
  91. For example, we declare a variable of type integer with the name
  92. k by writing:
  93.  
  94.     int k;
  95.  
  96.     On seeing the "int" part of this statement the compiler sets
  97. aside 2 bytes (on a PC) of memory to hold the value of the
  98. integer.  It also sets up a symbol table. And in that table it
  99. adds the symbol k and the address in memory where those 2 bytes
  100. were set aside.
  101.  
  102.     Thus, later if we write:
  103.  
  104.     k = 2;
  105.  
  106. at run time we expect that the value 2 will be placed in that
  107. memory location reserved for the storage of the value of k.
  108.  
  109.     In a sense there are two "values" associated with k, one
  110. being the value of the integer stored there (2 in the above
  111. example) and the other being the "value" of the memory location
  112. where it is stored, i.e. the address of k.  Some texts refer to
  113. these two values with the nomenclature rvalue (right value,
  114. pronounced "are value") and lvalue (left value, pronunced "el
  115. value") respectively.
  116.  
  117.     The lvalue is the value permitted on the left side of the
  118. assignment operator '=' (i.e. the address where the result of
  119. evaluation of the right side ends up).  The rvalue is that which
  120. is on the right side of the assignment statment, the '2' above.
  121. Note that rvalues cannot be used on the left side of the
  122. assignment statement.  Thus:    2 = k;   is illegal.
  123.  
  124.     Okay, now consider:
  125.  
  126.     int j, k;
  127.     k = 2;
  128.     j = 7;    <-- line 1
  129.     k = j;    <-- line 2
  130.  
  131.     In the above, the compiler interprets the j in line 1 as the
  132. address of the variable j (its lvalue) and creates code to copy
  133. the value 7 to that address.  In line 2, however, the j is
  134. interpreted as its rvalue (since it is on the right hand side of
  135. the assignment operator '=').  That is, here the j refers to the
  136. value _stored_ at the memory location set aside for j, in this
  137. case 7.  So, the 7 is copied to the address designated by the
  138. lvalue of k.
  139.  
  140.     In all of these examples, we are using 2 byte integers so all
  141. copying of rvalues from one storage location to the other is done
  142. by copying 2 bytes.  Had we been using long integers, we would be
  143. copying 4 bytes.
  144.  
  145.     Now, let's say that we have a reason for wanting a variable
  146. designed to hold an lvalue (an address).  The size required to
  147. hold such a value depends on the system.  On older desk top
  148. computers with 64K of memory total, the address of any point in
  149. memory can be contained in 2 bytes.  Computers with more memory
  150. would require more bytes to hold an address.  Some computers,
  151. such as the IBM PC might require special handling to hold a
  152. segment and offset under certain circumstances.  The actual size
  153. required is not too important so long as we have a way of
  154. informing the compiler that what we want to store is an address.
  155.  
  156.     Such a variable is called a "pointer variable" (for reasons
  157. which will hopefully become clearer a little later).  In C when
  158. we define a pointer variable we do so by preceding its name with
  159. an asterisk.  In C we also give our pointer a type which, in this
  160. case, refers to the type of data stored at the address we will be
  161. storing in our pointer.  For example, consider the variable
  162. definition:
  163.  
  164.     int *ptr;
  165.  
  166.     ptr is the _name_ of our variable (just as 'k' was the name
  167. of our integer variable).  The '*' informs the compiler that we
  168. want a pointer variable, i.e. to set aside however many bytes is
  169. required to store an address in memory.  The "int" says that we
  170. intend to use our pointer variable to store the address of an
  171. integer. Such a pointer is said to "point to" an integer.  Note,
  172. however, that when we wrote  "int k;" we did not give k a value.
  173. If this definiton was made outside of any function many compilers
  174. will initialize it to zero.  Simlarly, ptr has no value, that is
  175. we haven't stored an address in it in the above definition.  In
  176. this case, again if the definition is outside of any function, it
  177. is intialized to a value #defined by your compiler as NULL.  It
  178. is called a NULL pointer.  While in most cases NULL is #defined
  179. as zero, it need not be.  That is, different compilers handle
  180. this differently.  Also note that while zero is an integer, NULL
  181. need not be.
  182.  
  183.     But, back to using our new variable ptr.  Suppose now that we
  184. want to store in ptr the address of our integer variable k.  To
  185. do this we use the unary '&' operator and write:
  186.  
  187.     ptr = &k;
  188.  
  189.     What the '&' operator does is retrieve the lvalue (address)
  190. of k, even though k is on the right hand side of the assignment
  191. operator '=', and copies that to the contents of our pointer ptr.
  192. Now, ptr is said to "point to" k.  Bear with us now, there is
  193. only one more operator we need to discuss.
  194.  
  195.     The "dereferencing operator" is the asterisk and it is used
  196. as follows:
  197.  
  198.     *ptr = 7;
  199.  
  200. will copy 7 to the address pointed to by ptr.  Thus if ptr
  201. "points to" (contains the address of) k, the above statement will
  202. set the value of k to 7.  That is, when we use the '*' this way
  203. we are refering to the value of that which ptr is pointing
  204. at, not the value of the pointer itself.
  205.  
  206.     Similarly, we could write:
  207.  
  208.     printf("%d\n",*ptr);
  209.  
  210. to print to the screen the integer value stored at the address
  211. pointed to by "ptr".
  212.  
  213.     One way to see how all this stuff fits together would be to
  214. run the following program and then review the code and the output
  215. carefully.
  216.  
  217. -------------------------------------------------
  218. #include <stdio.h>
  219.  
  220. int j, k;
  221. int *ptr;
  222.  
  223.  
  224. int main(void)
  225. {
  226.    j = 1;
  227.    k = 2;
  228.    ptr = &k;
  229.    printf("\n");
  230.    printf("j has the value %d and is stored at %p\n",j,&j);
  231.    printf("k has the value %d and is stored at %p\n",k,&k);
  232.    printf("ptr has the value %p and is stored at %p\n",ptr,&ptr);
  233.    printf("The value of the integer pointed to by ptr is %d\n",
  234.            *ptr);
  235.    return 0;
  236. }
  237. ---------------------------------------
  238. To review:
  239.  
  240.     A variable is defined by giving it a type and a name (e.g.
  241.      int k;)
  242.  
  243.     A pointer variable is defined by giving it a type and a name
  244.      (e.g. int *ptr) where the asterisk tells the compiler that
  245.      the variable named ptr is a pointer variable and the type
  246.      tells the compiler what type the pointer is to point to
  247.      (integer in this case).
  248.  
  249.     Once a variable is defined, we can get its address by
  250.      preceding its name with the unary '&' operator, as in &k.
  251.  
  252.     We can "dereference" a pointer, i.e. refer to the value of
  253.      that which it points to, by using the unary '*' operator as
  254.      in *ptr.
  255.  
  256.     An "lvalue" of a variable is the value of its address, i.e.
  257.      where it is stored in memory.  The "rvalue" of a variable is
  258.      the value stored in that variable (at that address).
  259.  
  260. ==================================================================
  261. CHAPTER 2: Pointer types and Arrays
  262.  
  263.     Okay, let's move on.  Let us consider why we need to identify
  264. the "type" of variable that a pointer points to, as in:
  265.  
  266.         int *ptr;
  267.  
  268.     One reason for doing this is so that later, once ptr "points
  269. to" something, if we write:
  270.  
  271.         *ptr = 2;
  272.  
  273. the compiler will know how many bytes to copy into that memory
  274. location pointed to by ptr.  If ptr was defined as pointing to an
  275. integer, 2 bytes would be copied, if a long, 4 bytes would be
  276. copied.  Similarly for floats and doubles the appropriate number
  277. will be copied.  But, defining the type that the pointer points
  278. to permits a number of other interesting ways a compiler can
  279. interpret code.  For example, consider a block in memory
  280. consisting if ten integers in a row.  That is, 20 bytes of memory
  281. are set aside to hold 10 integer.
  282.  
  283.     Now, let's say we point our integer pointer ptr at the first
  284. of these integers.  Furthermore lets say that integer is located
  285. at memory location 100 (decimal).   What happens when we write:
  286.  
  287.     ptr + 1;
  288.  
  289.     Because the compiler "knows" this is a pointer (i.e. its
  290. value is an address) and that it points to an integer (its
  291. current address, 100, is the address of an integer), it adds 2 to
  292. ptr instead of 1, so the pointer "points to" the _next_
  293. _integer_, at memory location 102.  Similarly, were the ptr
  294. defined as a pointer to a long, it would add 4 to it instead of
  295. 1.  The same goes for other data types such as floats, doubles,
  296. or even user defined data types such as structures.
  297.  
  298.     Similarly, since ++ptr and ptr++ are both equivalent to
  299. ptr + 1 (though the point in the program when ptr is incremented
  300. may be different), incrementing a pointer using the unary ++
  301. operator, either pre- or post-, increments the address it stores
  302. by the amount sizeof(type) (i.e. 2 for an integer, 4 for a long,
  303. etc.).
  304.  
  305.     Since a block of 10 integers located contiguously in memory
  306. is, by definition, an array of integers, this brings up an
  307. interesting relationship between arrays and pointers.
  308.  
  309.     Consider the following:
  310.  
  311.     int my_array[] = {1,23,17,4,-5,100};
  312.  
  313.     Here we have an array containing 6 integers.  We refer to
  314. each of these integers by means of a subscript to my_array, i.e.
  315. using my_array[0] through my_array[5].  But, we could
  316. alternatively access them via a pointer as follows:
  317.  
  318.     int *ptr;
  319.  
  320.     ptr = &my_array[0];       /* point our pointer at the first
  321.                                  integer in our array */
  322.  
  323.     And then we could print out our array either using the array
  324. notation or by dereferencing our pointer.  The following code
  325. illustrates this:
  326. ------------------------------------------------------
  327. #include <stdio.h>
  328.  
  329. int my_array[] = {1,23,17,4,-5,100};
  330. int *ptr;
  331.  
  332. int main(void)
  333. {
  334.     int i;
  335.     ptr = &my_array[0];     /* point our pointer to the array */
  336.     printf("\n\n");
  337.     for(i = 0; i < 6; i++)
  338.     {
  339.       printf("my_array[%d] = %d   ",i,my_array[i]);   /*<-- A */
  340.       printf("ptr + %d = %d\n",i, *(ptr + i));        /*<-- B */
  341.     }
  342.     return 0;
  343. }
  344. ----------------------------------------------------
  345.    Compile and run the above program and carefully note lines A
  346. and B and that the program prints out the same values in either
  347. case.  Also note how we dereferenced our pointer in line B, i.e.
  348. we first added i to it and then dereferenced the the new pointer.
  349. Change line B to read:
  350.  
  351.      printf("ptr + %d = %d\n",i, *ptr++);
  352.  
  353. and run it again... then change it to:
  354.  
  355.      printf("ptr + %d = %d\n",i, *(++ptr));
  356.  
  357. and try once more.  Each time try and predict the outcome and
  358. carefully look at the actual outcome.
  359.  
  360.     In C, the standard states that wherever we might use
  361. &var_name[0] we can replace that with var_name, thus in our code
  362. where we wrote:
  363.  
  364.         ptr = &my_array[0];
  365.  
  366.     we can write:
  367.  
  368.         ptr = my_array;     to achieve the same result.
  369.  
  370.     This leads many texts to state that the name of an array is a
  371. pointer.  While this is true, I prefer to mentally think "the
  372. name of the array is a _constant_ pointer".  Many beginners
  373. (including myself when I was learning) forget that _constant_
  374. qualifier.  In my opinon this leads to some confusion.  For
  375. example, while we can write ptr = my_array; we cannot write
  376.  
  377.     my_array = ptr;
  378.  
  379.     The reason is that the while ptr is a variable, my_array is a
  380. constant.  That is, the location at which the first element of
  381. my_array will be stored cannot be changed once my_array[] has
  382. been declared.
  383.  
  384. Modify the example program above by changing
  385.  
  386.     ptr = &my_array[0];     to     ptr = my_array;
  387.  
  388. and run it again to verify the results are identical.
  389.  
  390.     Now, let's delve a little further into the difference between
  391. the names "ptr" and "my_array" as used above.  We said that
  392. my_array is a constant pointer.  What do we mean by that?  Well,
  393. to understand the term "constant" in this sense, let's go back to
  394. our definition of the term "variable".  When we define a variable
  395. we set aside a spot in memory to hold the value of the
  396. appropriate type.  Once that is done the name of the variable can
  397. be interpreted in one of two ways.  When used on the left side of
  398. the assignment operator, the compiler interprets it as the memory
  399. location to which to move that which lies on the right side of
  400. the assignment operator.  But, when used on the right side of the
  401. assignment operator, the name of a variable is interpreted to
  402. mean the contents stored at that memory address set aside to hold
  403. the value of that variable.
  404.  
  405.     With that in mind, let's now consider the simplest of
  406. constants, as in:
  407.  
  408.     int i, k;
  409.     i = 2;
  410.  
  411.     Here, while "i" is a variable and then occupies space in the
  412. data portion of memory, "2" is a constant and, as such, instead
  413. of setting aside memory in the data segment, it is imbedded
  414. directly in the code segment of memory.  That is, while writing
  415. something like k = i;  tells the compiler to create code which at
  416. run time will look at memory location &i to determine the value
  417. to be moved to k, code created by  i = 2;  simply puts the '2' in
  418. the code and there is no referencing of the data segment.
  419.  
  420.     Similarly, in the above, since "my_array" is a constant, once
  421. the compiler establishes where the array itself is to be stored,
  422. it "knows" the address of my_array[0] and on seeing:
  423.  
  424.     ptr = my_array;
  425.  
  426. it simply uses this address as a constant in the code segment and
  427. there is no referencing of the data segment beyond that.
  428.  
  429.     Well, that's a lot of technical stuff to digest and I don't
  430. expect a beginner to understand all of it on first reading.  With
  431. time and experimentation you will want to come back and re-read
  432. the first 2 chapters.  But for now, let's move on to the
  433. relationship between pointers, character arrays, and strings.
  434.  
  435. ==================================================================
  436. CHAPTER 3:  Pointers and Strings
  437.  
  438.     The study of strings is useful to further tie in the
  439. relationship between pointers and arrays.  It also makes it easy
  440. to illustrate how some of the standard C string functions can be
  441. implemented. Finally it illustrates how and when pointers can and
  442. should be passed to functions.
  443.  
  444.     In C, strings are arrays of characters.  This is not
  445. necessarily true in other languages.  In Pascal or (most versions
  446. of) Basic, strings are treated differently from arrays.  To start
  447. off our discussion we will write some code which, while preferred
  448. for illustrative purposes, you would probably never write in an
  449. actual program.  Consider, for example:
  450.  
  451.     char my_string[40];
  452.  
  453.     my_string[0] = 'T';
  454.     my_string[1] = 'e';
  455.     my_string[2] = 'd':
  456.     my_string[3] = '\0';
  457.  
  458.     While one would never build a string like this, the end
  459. result is a string in that it is an array of characters
  460. _terminated_with_a_nul_character_.  By definition, in C, a string
  461. is an array of characters terminated with the nul character. Note
  462. that "nul" is _not_ the same as "NULL".  The nul refers to a zero
  463. as is defined by the escape sequence '\0'.  That is it occupies
  464. one byte of memory.  The NULL, on the other hand, is the value of
  465. an uninitialized pointer and pointers require more than one byte
  466. of storage.  NULL is #defined in a header file in your C
  467. compiler, nul may not be #defined at all.
  468.  
  469.     Since writing the above code would be very time consuming, C
  470. permits two alternate ways of achieving the same thing.  First,
  471. one might write:
  472.  
  473.     char my_string[40] = {'T', 'e', 'd', '\0',};
  474.  
  475.     But this also takes more typing than is convenient.  So, C
  476. permits:
  477.  
  478.     char my_string[40] = "Ted";
  479.  
  480.     When the double quotes are used, instead of the single quotes
  481. as was done in the previous examples, the nul character ( '\0' )
  482. is automatically appended to the end of the string.
  483.  
  484.     In all of the above cases, the same thing happens.  The
  485. compiler sets aside an contiguous block of memory 40 bytes long
  486. to hold characters and initialized it such that the first 4
  487. characters are Ted\0.
  488.  
  489.     Now, consider the following program:
  490.  
  491. ------------------program 3.1-------------------------------------
  492. #include <stdio.h>
  493.  
  494. char strA[80] = "A string to be used for demonstration purposes";
  495. char strB[80];
  496.  
  497. int main(void)
  498. {
  499.    char *pA;     /* a pointer to type character */
  500.    char *pB;     /* another pointer to type character */
  501.    puts(strA);   /* show string A */
  502.    pA = strA;    /* point pA at string A */
  503.    puts(pA);     /* show what pA is pointing to */
  504.    pB = strB;    /* point pB at string B */
  505.    putchar('\n');       /* move down one line on the screen */
  506.    while(*pA != '\0')   /* line A (see text) */
  507.    {
  508.      *pB++ = *pA++;     /* line B (see text) */
  509.    }
  510.    *pB = '\0';          /* line C (see text) */
  511.    puts(strB);          /* show strB on screen */
  512.    return 0;
  513. }
  514. --------- end program 3.1 -------------------------------------
  515.  
  516.     In the above we start out by defining two character arrays of
  517. 80 characters each.  Since these are globally defined, they are
  518. initialized to all '\0's first.  Then, strA has the first 42
  519. characters initialized to the string in quotes.
  520.  
  521.     Now, moving into the code, we define two character pointers
  522. and show the string on the screen.  We then "point" the ponter pA
  523. at strA.  That is, by means of the assignment statement we copy
  524. the address of strA[0] into our variable pA.  We now use puts()
  525. to show that which is pointed to by pA on the screen.  Consider
  526. here that the function prototype for puts() is:
  527.  
  528.     int puts(const char *s);
  529.  
  530.     For the moment, ignore the "const".  The parameter passed to
  531. puts is a pointer, that is the _value_ of a pointer (since all
  532. parameters in C are passed by value), and the value of a pointer
  533. is the address to which it points, or, simply, an address.  Thus
  534. when we write:
  535.  
  536.     puts(strA);        as we have seen, we are passing the
  537.  
  538. address of strA[0].  Similarly, when we write:
  539.  
  540.     puts(pA);          we are passing the same address, since
  541.  
  542. we have set pA = strA;
  543.  
  544.     Given that, follow the code down to the while() statement on
  545. line A.  Line A states:
  546.  
  547.     While the character pointed to by pA (i.e. *pA) is not a nul
  548. character (i.e. the terminating '\0'), do the following:
  549.  
  550.     line B states:  copy the character pointed to by pA to the
  551. space pointed to by pB, then increment pA so it points to the
  552. next character and pB so it points to the next space.
  553.  
  554.     Note that when we have copied the last character, pA now
  555. points to the terminating nul character and the loop ends.
  556. However, we have not copied the nul character.  And, by
  557. definition a string in C _must_ be nul terminated.  So, we add
  558. the nul character with line C.
  559.  
  560.     It is very educational to run this program with your debugger
  561. while watching strA, strB, pA and pB and single stepping through
  562. the program.  It is even more educational if instead of simply
  563. defining strB[] as has been done above, initialize it also with
  564. something like:
  565.  
  566.  strB[80] = "12345678901234567890123456789012345678901234567890"
  567.  
  568. where the number of digits used is greater than the length of
  569. strA and then repeat the single stepping procedure while watching
  570. the above variables.  Give these things a try!
  571.  
  572.     Of course, what the above program illustrates is a simple way
  573. of copying a string.  After playing with the above until you have
  574. a good understanding of what is happening, we can proceed to
  575. creating our own replacement for the standard strcpy() that comes
  576. with C.  It might look like:
  577.  
  578.    char *my_strcpy(char *destination, char *source)
  579.    {
  580.         char *p = destination
  581.         while (*source != '\0')
  582.         {
  583.            *p++ = *source++;
  584.         }
  585.         *p = '\0';
  586.         return destination.
  587.    }
  588.  
  589.     In this case, I have followed the practice used in the
  590. standard routine of returning a pointer to the destination.
  591.  
  592.     Again, the function is designed to accept the values of two
  593. character pointers, i.e. addresses, and thus in the previous
  594. program we could write:
  595.  
  596. int main(void)
  597. {
  598.   my_strcpy(strB, strA);
  599.   puts(strB);
  600. }
  601.  
  602.     I have deviated slightly from the form used in standard C
  603. which would have the prototype:
  604.  
  605.     char *my_strcpy(char *destination, const char *source);
  606.  
  607.     Here the "const" modifier is used to assure the user that the
  608. function will not modify the contents pointed to by the source
  609. pointer.  You can prove this by modifying the function above, and
  610. its prototype, to include the "const" modifier as shown.  Then,
  611. within the function you can add a statement which attempts to
  612. change the contents of that which is pointed to by source, such
  613. as:
  614.  
  615.     *source = 'X';
  616.  
  617. which would normally change the first character of the string to
  618. an X.  The const modifier should cause your compiler to catch
  619. this as an error.  Try it and see.
  620.  
  621.     Now, let's consider some of the things the above examples
  622. have shown us.  First off, consider the fact that *ptr++ is to be
  623. interpreted as returning the value pointed to by ptr and then
  624. incrementing the pointer value.  On the other hand, note that
  625. this has to do with the precedence of the operators.  Were we to
  626. write (*ptr)++ we would increment, not the pointer, but that
  627. which the pointer points to!  i.e. if used on the first character
  628. of the above example string the 'T' would be incremented to a
  629. 'U'.  You can write some simple example code to illustrate this.
  630.  
  631.     Recall again that a string is nothing more than an array
  632. of characters.  What we have done above is deal with copying
  633. an array.  It happens to be an array of characters but the
  634. technique could be applied to an array of integers, doubles,
  635. etc.  In those cases, however, we would not be dealing with
  636. strings and hence the end of the array would not be
  637. _automatically_ marked with a special value like the nul
  638. character.  We could implement a version that relied on a
  639. special value to identify the end. For example, we could
  640. copy an array of postive integers by marking the end with a
  641. negative integer.  On the other hand, it is more usual that
  642. when we write a function to copy an array of items other
  643. than strings we pass the function the number of items to be
  644. copied as well as the address of the array, e.g. something
  645. like the following prototype might indicate:
  646.  
  647.     void int_copy(int *ptrA, int *ptrB, int nbr);
  648.  
  649. where nbr is the number of integers to be copied.  You might want
  650. to play with this idea and create an array of integers and see if
  651. you can write the function int_copy() and make it work.
  652.  
  653.     Note that this permits using functions to manipulate very
  654. large arrays.  For example, if we have an array of 5000 integers
  655. that we want to manipulate with a function, we need only pass to
  656. that function the address of the array (and any auxiliary
  657. information such as nbr above, depending on what we are doing).
  658. The array itself does _not_ get passed, i.e. the whole array is
  659. not copied and put on the stack before calling the function, only
  660. its address is sent.
  661.  
  662.     Note that this is different from passing, say an integer, to
  663. a function.  When we pass an integer we make a copy of the
  664. integer, i.e. get its value and put it on the stack.  Within the
  665. function any manipulation of the value passed can in no way
  666. effect the original integer.  But, with arrays and pointers we
  667. can pass the address of the variable and hence manipulate the
  668. values of of the original variables.
  669.  
  670. ==================================================================
  671. CHAPTER 4: More on Strings
  672.  
  673.     Well, we have progressed quite aways in a short time!  Let's
  674. back up a little and look at what was done in Chapter 3 on
  675. copying of strings but in a different light.  Consider the
  676. following function:
  677.  
  678.    char *my_strcpy(char dest[], char source[])
  679.    {
  680.         int i = 0;
  681.  
  682.         while (source[i] != '\0')
  683.         {
  684.            dest[i] = source[i];
  685.            i++;
  686.         }
  687.         dest[i] = '\0';
  688.         return dest;
  689.    }
  690.  
  691.     Recall that strings are arrays of characters.  Here we have
  692. chosen to use array notation instead of pointer notation to do
  693. the actual copying.  The results are the same, i.e. the string
  694. gets copied using this notation just as accurately as it did
  695. before.  This raises some interesting points which we will
  696. discuss.
  697.  
  698.     Since parameters are passed by value, in both the passing of
  699. a character pointer or the name of the array as above, what
  700. actually gets passed is the address of the first element of each
  701. array.  Thus, the numerical value of the parameter passed is the
  702. same whether we use a character pointer or an array name as a
  703. parameter.  This would tend to imply that somehow:
  704.  
  705.         source[i]  is the same as  *(p+i);
  706.  
  707. In fact, this is true, i.e wherever one writes   a[i]  it can be
  708. replaced with  *(a + i) without any problems.  In fact, the
  709. compiler will create the same code in either case.   Now, looking
  710. at this last expression, part of it..  (a + i)  is a simple
  711. addition using the + operator and the rules of c state that such
  712. an expression is commutative.  That is   (a + i) is identical to
  713. (i + a).  Thus we could write *(i + a) just as easily as
  714. *(a + i).
  715.  
  716.     But *(i + a) could have come from i[a] !  From all of this
  717. comes the curious truth that if:
  718.  
  719.     char a[20];
  720.     int i;
  721.  
  722.     writing    a[3] = 'x';   is the same as writing
  723.  
  724.                3[a] = 'x';
  725.  
  726.     Try it!  Set up an array of characters, integers or longs,
  727. etc. and assigned the 3rd or 4th element a value using the
  728. conventional approach and then print out that value to be sure
  729. you have that working.  Then reverse the array notation as I have
  730. done above.  A good compiler will not balk and the results will
  731. be identical.   A curiosity... nothing more!
  732.  
  733.     Now, looking at our function above, when we write:
  734.  
  735.         dest[i] = source[i];
  736.  
  737.     this gets interpreted by C to read:
  738.  
  739.         *(dest + i) = *(source + i);
  740.  
  741.     But, this takes 2 additions for each value taken on by i.
  742. Additions, generally speaking, take more time than
  743. incrementations (such as those done using the ++ operator as in
  744. i++).  This may not be true in modern optimizing compilers, but
  745. one can never be sure.  Thus, the pointer version may be a bit
  746. faster than the array version.
  747.  
  748.     Another way to speed up the pointer version would be to
  749. change:
  750.  
  751.     while (*source != '\0')     to simply    while (*source)
  752.  
  753. since the value within the parenthesis will go to zero (FALSE) at
  754. the same time in either case.  
  755.  
  756.     At this point you might want to experiment a bit with writing
  757. some of your own programs using pointers.  Manipulating strings
  758. is a good place to experiment.  You might want to write your own
  759. versions of such standard functions as:
  760.  
  761.             strlen();
  762.             strcat();
  763.             strchr();
  764.  
  765. and any others you might have on your system.
  766.  
  767.     We will come back to strings and their manipulation through
  768. pointers in a future chapter.  For now, let's move on and discuss
  769. structures for a bit.
  770.  
  771. ==================================================================
  772. CHAPTER 5: Pointers and Structures
  773.  
  774.     As you may know, we can declare the form of a block of data
  775. containing different data types by means of a structure
  776. declaration.  For example, a personnel file might contain
  777. structures which look something like:
  778.  
  779.   struct tag{
  780.        char lname[20];        /* last name */
  781.        char fname[20];        /* first name */
  782.        int age;               /* age */
  783.        float rate;            /* e.g. 12.75 per hour */
  784.        };
  785.  
  786.     Let's say we have an bunch of these structures in a disk file
  787. and we want to read each one out and print out the first and last
  788. name of each one so that we can have a list of the people in our
  789. files.  The remaining information will not be printed out.  We
  790. will want to do this printing with a function call and pass to
  791. that function a pointer to the structure at hand.  For
  792. demonstration purposes I will use only one structure for now. But
  793. realize the goal is the writing of the function, not the reading
  794. of the file which, presumably, we know how to do.
  795.  
  796.     For review, recall that we can access structure members with
  797. the dot operator as in:
  798.  
  799. --------------- program 5.1 ------------------
  800. #include <stdio.h>
  801. #include <string.h>
  802.  
  803. struct tag{
  804.        char lname[20];      /* last name */
  805.        char fname[20];      /* first name */
  806.        int age;             /* age */
  807.        float rate;          /* e.g. 12.75 per hour */
  808.        };
  809.  
  810. struct tag my_struct;       /* declare the structure m_struct */
  811.  
  812. int main(void)
  813. {
  814.   strcpy(my_struct.lname,"Jensen");
  815.   strcpy(my_struct.fname,"Ted");
  816.   printf("\n%s ",my_struct.fname);
  817.   printf("%s\n",my_struct.lname);
  818.   return 0;
  819. }
  820. -------------- end of program 5.1 --------------
  821.  
  822.     Now, this particular structure is rather small compared to
  823. many used in C programs.  To the above we might want to add:
  824.  
  825.   date_of_hire;
  826.   date_of_last_raise;
  827.   last_percent_increase;
  828.   emergency_phone;
  829.   medical_plan;
  830.   Social_S_Nbr;
  831.   etc.....
  832.  
  833.     Now, if we have a large number of employees, what we want to
  834. do manipulate the data in these structures by means of functions.
  835. For example we might want a function print out the name of any
  836. structure passed to it.  However, in the original C (Kernighan &
  837. Ritchie) it was not possible to pass a structure, only a pointer
  838. to a structure could be passed.  In ANSI C, it is now permissible
  839. to pass the complete structure.  But, since our goal here is to
  840. learn more about pointers, we won't pursue that.
  841.  
  842.     Anyway, if we pass the whole structure it means there must be
  843. enough room on the stack to hold it.  With large structures this
  844. could prove to be a problem.  However, passing a pointer uses a
  845. minimum amount of stack space.
  846.  
  847.     In any case, since this is a discussion of pointers, we will
  848. discuss how we go about passing a pointer to a structure and then
  849. using it within the function.
  850.  
  851.     Consider the case described, i.e. we want a function that
  852. will accept as a parameter a pointer to a structure and from
  853. within that function we want to access members of the structure.
  854. For example we want to print out the name of the employee in our
  855. example structure.
  856.  
  857.     Okay, so we know that our pointer is going to point to a
  858. structure declared using struct tag.  We define such a pointer
  859. with the definition:
  860.  
  861.     struct tag *st_ptr;
  862.  
  863. and we point it to our example structure with:
  864.  
  865.     st_ptr = &my_struct;
  866.  
  867.     Now, we can access a given member by de-referencing the
  868. pointer. But, how do we de-reference the pointer to a structure?
  869. Well, consider the fact that we might want to use the pointer to
  870. set the age of the employee.  We would write:
  871.  
  872.     (*st_ptr).age = 63;
  873.  
  874.     Look at this carefully.  It says, replace that within the
  875. parenthesis with that which st_ptr points to, which is the
  876. structure my_struct.  Thus, this breaks down to the same as
  877. my_struct.age.
  878.  
  879.     However, this is a fairly often used expression and the
  880. designers of C have created an alternate syntax with the same
  881. meaning which is:
  882.  
  883.     st_ptr->age = 63;
  884.  
  885.     With that in mind, look at the following program:
  886.  
  887. ------------ program 5.2 --------------
  888.  
  889. #include <stdio.h>
  890. #include <string.h>
  891.  
  892. struct tag{                   /* the structure type */
  893.        char lname[20];        /* last name */
  894.        char fname[20];        /* first name */
  895.        int age;               /* age */
  896.        float rate;            /* e.g. 12.75 per hour */
  897.        };
  898.  
  899. struct tag my_struct;         /* define the structure */
  900.  
  901. void show_name(struct tag *p);    /* function prototype */
  902.  
  903. int main(void)
  904. {
  905.   struct tag *st_ptr;         /* a pointer to a structure */
  906.   st_ptr = &my_struct;        /* point the pointer to my_struct */
  907.   strcpy(my_struct.lname,"Jensen");
  908.   strcpy(my_struct.fname,"Ted");
  909.   printf("\n%s ",my_struct.fname);
  910.   printf("%s\n",my_struct.lname);
  911.   my_struct.age = 63;
  912.   show_name(st_ptr);          /* pass the pointer */
  913.   return 0;
  914. }
  915.  
  916.  
  917. void show_name(struct tag *p)
  918. {
  919.   printf("\n%s ", p->fname);     /* p points to a structure */
  920.   printf("%s ", p->lname);
  921.   printf("%d\n", p->age);
  922. }
  923. -------------------- end of program 5.2 ----------------
  924.  
  925.     Again, this is a lot of information to absorb at one time.
  926. The reader should compile and run the various code snippets and
  927. using a debugger monitor things like my_struct and p while single
  928. stepping through the main and following the code down into the
  929. function to see what is happening.
  930.  
  931. ==================================================================
  932. CHAPTER 6:  Some more on Strings, and Arrays of Strings
  933.  
  934.    Well, let's go back to strings for a bit.  In the following
  935. all assignments are to be understood as being global, i.e. made
  936. outside of any function, including main.
  937.  
  938.    We pointed out in an earlier chapter that we could write:
  939.  
  940.    char my_string[40] = "Ted";
  941.  
  942. which would allocate space for a 40 byte array and put the string
  943. in the first 4 bytes (three for the characters in the quotes and
  944. a 4th to handle the terminating '\0'.
  945.  
  946.     Actually, if all we wanted to do was store the name "Ted" we
  947. could write:
  948.  
  949.       char my_name[] = "Ted";
  950.  
  951. and the compiler would count the characters, leave room for the
  952. nul character and store the total of the four characters in memory
  953. the location of which would be returned by the array name, in this
  954. case my_string.
  955.  
  956.     In some code, instead of the above, you might see:
  957.  
  958.      char *my_name = "Ted";
  959.  
  960. which is an alternate approach.  Is there a difference between
  961. these?  The answer is.. yes.  Using the array notation 4 bytes of
  962. storage in the static memory block are taken up, one for each
  963. character and one for the nul character.  But, in the pointer
  964. notation the same 4 bytes required, _plus_ N bytes to store the
  965. pointer variable my_name (where N depends on the system but is
  966. usually a minimum of 2 bytes and can be 4 or more).
  967.  
  968.     In the array notation, my_name is a constant (not a
  969. variable).  In the pointer notation my_name is a variable.  As to
  970. which is the _better_ method, that depends on what you are going
  971. to do within the rest of the program.
  972.  
  973.     Let's now go one step further and consider what happens if
  974. each of these definitions are done within a function as opposed
  975. to globally outside the bounds of any function.
  976.  
  977. void my_function_A(char *ptr)
  978. {
  979.   char a[] = "ABCDE";
  980.   .
  981.   .
  982. }
  983.  
  984. void my_function_B(char *ptr)
  985. {
  986.   char *cp = "ABCDE";
  987.   .
  988.   .
  989. }
  990.  
  991.     Here we are dealing with automatic variables in both cases.
  992. In my_function_A the automatic variable is the character array
  993. a[]. In my_function_B it is the pointer cp.  While C is designed
  994. in such a way that a stack is not required on those processors
  995. which don't use them, my particular processor (80286) has a
  996. stack.  I wrote a simple program incorporating functions similar
  997. to those above and found that in my_function_A the 5 characters
  998. in the string were all stored on the stack.  On the other hand,
  999. in my_function_B, the 5 characters were stored in the data space
  1000. and the pointer was stored on the stack.
  1001.  
  1002.     By making a[] static I could force the compiler to place the
  1003. 5 characters in the data space as opposed to the stack.  I did
  1004. this exercise to point out just one more difference between
  1005. dealing with arrays and dealing with pointers.  By the way, array
  1006. initialization of automatic variables as I have done in
  1007. my_function_A was illegal in the older K&R C and only "came of
  1008. age" in the newer ANSI C.  A fact that may be important when one
  1009. is considering portabilty and backwards compatability.
  1010.  
  1011.     As long as we are discussing the relationship/differences
  1012. between pointers and arrays, let's move on to multi-dimensional
  1013. arrays.  Consider, for example the array:
  1014.  
  1015.     char multi[5][10];
  1016.  
  1017.     Just what does this mean?   Well, let's consider it in the
  1018. following light.
  1019.  
  1020.         char multi[5][10];
  1021.         ^^^^^^^^^^^^^
  1022.  
  1023.     If we take the first, underlined, part above and consider it
  1024. to be a variable in its own right, we have an array of 10
  1025. characters with the "name"  multi[5].  But this name, in itself,
  1026. implies an array of 5 somethings.  In fact, it means an array of
  1027. five 10 character arrays.  Hence we have an array of arrays.  In
  1028. memory we might think of this as looking like:
  1029.  
  1030.       multi[0] = "0123456789"
  1031.       multi[1] = "abcdefghij"
  1032.       multi[2] = "ABCDEFGHIJ"
  1033.       multi[3] = "9876543210"
  1034.       multi[4] = "JIHGFEDCBA"
  1035.  
  1036. with individual elements being, for example:
  1037.  
  1038.       multi[0][3] = '3'
  1039.       multi[1][7] = 'h'
  1040.       multi[4][0] = 'J'
  1041.  
  1042.     Since arrays are to be contiguous, our actual memory block
  1043. for the above should look like:
  1044.  
  1045.     "0123456789abcdefghijABCDEFGHIJ9876543210JIHGFEDCBA"
  1046.  
  1047.     Now, the compiler knows how many columns are present in the
  1048. array so it can interpret multi + 1 as the address of the 'a' in
  1049. the 2nd row above.  That is, it adds 10, the number of columns,
  1050. to get this location.  If we were dealing with integers and an
  1051. array with the same dimension the compiler would add
  1052. 10*sizeof(int) which, on my machine, would be 20.  Thus, the
  1053. address of the "9" in the 4th row above would be &multi[3][0] or
  1054. *(multi + 3) in pointer notation.  To get to the content of the
  1055. 2nd element in row 3 we add 1 to this address and dereference the
  1056. result as in
  1057.  
  1058.     *(*(multi + 3) + 1)
  1059.  
  1060.     With a little thought we can see that:
  1061.  
  1062.     *(*(multi + row) + col)    and
  1063.     multi[row][col]            yield the same results.
  1064.  
  1065.     The following program illustrates this using integer arrays
  1066. instead of character arrays.
  1067.  
  1068. ------------------- program 6.1 ----------------------
  1069. #include <stdio.h>
  1070.  
  1071. #define ROWS 5
  1072. #define COLS 10
  1073.  
  1074. int multi[ROWS][COLS];
  1075.  
  1076. int main(void)
  1077. {
  1078.   int row, col;
  1079.   for (row = 0; row < ROWS; row++)
  1080.     for(col = 0; col < COLS; col++)
  1081.       multi[row][col] = row*col;
  1082.   for (row = 0; row < ROWS; row++)
  1083.     for(col = 0; col < COLS; col++)
  1084.     {
  1085.       printf("\n%d  ",multi[row][col]);
  1086.       printf("%d ",*(*(multi + row) + col));
  1087.     }
  1088.   return 0;
  1089. }
  1090. ----------------- end of program 6.1 ---------------------
  1091.  
  1092.     Because of the double de-referencing required in the pointer
  1093. version, the name of a 2 dimensional array is said to be a
  1094. pointer to a pointer.  With a three dimensional array we would be
  1095. dealing with an array of arrays of arrays and a pointer to a
  1096. pointer to a pointer.  Note, however, that here we have initially
  1097. set aside the block of memory for the array by defining it using
  1098. array notation.  Hence, we are dealing with an constant, not a
  1099. variable.  That is we are talking about a fixed pointer not a
  1100. variable pointer.  The dereferencing function used above permits
  1101. us to access any element in the array of arrays without the need
  1102. of changing the value of that pointer (the address of multi[0][0]
  1103. as given by the symbol "multi").
  1104.  
  1105. EPILOG:
  1106.  
  1107.     I have written the preceding material to provide an
  1108. introduction to pointers for newcomers to C.  In C, the more one
  1109. understands about pointers the greater flexibility one has in the
  1110. writing of code.  The above has just scratched the surface of the
  1111. subject. In time I hope to expand on this material.  Therefore,
  1112. if you have questions, comments, criticisms, etc. concerning that
  1113. which has been presented, I would greatly appreciate your
  1114. contacting me using one of the mail addresses cited in the
  1115. Introduction.
  1116.  
  1117. Ted Jensen
  1118.