home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / PTRTUTOR.TXT < prev    next >
Text File  |  1997-07-05  |  90KB  |  2,473 lines

  1. +++Date last modified: 05-Jul-1997
  2.  
  3. PTRTUT03.TXT   6/1/96
  4.  
  5.            A TUTORIAL ON POINTERS AND ARRAYS IN C
  6.                      by Ted Jensen
  7.                       Version 0.3
  8.       This material is hereby placed in the public domain.
  9.  
  10.                     TABLE OF CONTENTS
  11.  
  12.         Preface
  13.  
  14.         Introduction
  15.  
  16.         Chapter 1:  What is a Pointer?
  17.  
  18.         Chapter 2:  Pointer Types and Arrays.
  19.  
  20.         Chapter 3:  Pointers and Strings
  21.  
  22.         Chapter 4:  More on Strings
  23.  
  24.         Chapter 5:  Pointers and Structures
  25.  
  26.         Chapter 6:  More on Strings and Arrays of Strings
  27.  
  28.         Chapter 7:  More on Multi-Dimensional Arrays
  29.  
  30.         Chapter 8:  Pointers to Arrays
  31.  
  32.         Chapter 9:  Pointers and Dynamic Allocation of Memory
  33.  
  34.         Chapter 10: Pointers to Functions
  35.  
  36.         Epilog
  37.  
  38. ->============================================================
  39. PREFACE
  40.  
  41.     This document is intended to introduce pointers to beginning
  42. programmers in the C programming language.  Over several years of
  43. reading and contributing to various conferences on C including
  44. those on the FidoNet and UseNet, I have noted a large number of
  45. newcomers to C appear to have a difficult time in grasping the
  46. fundamentals of pointers.  I therefore undertook the task of
  47. trying to explain them in plain language with lots of examples.
  48.  
  49.     The first version of this document was placed in the public
  50. domain, as is this one.  It was picked up by Bob Stout who
  51. included it as a file called PTR-HELP.TXT in his widely
  52. distributed collection of SNIPPETS.  Since that release, I have
  53. added a significant amount of material and made some minor
  54. corrections in the original work.
  55.  
  56. Acknowledgements:
  57.  
  58.     There are so many people who have unknowingly contributed to
  59. this work because of the questions they have posed in the FidoNet
  60. C Echo, or the UseNet Newsgroup comp.lang.c, or several other
  61. conferences in other networks, that it would be impossible to
  62. list them all.  Special thanks go to Bob Stout who was kind
  63. enough to include the first version of this material in his
  64. SNIPPETS file.
  65.  
  66. About the Author:
  67.  
  68.     Ted Jensen is a retired Electronics Engineer who worked as a
  69. hardware designer or manager of hardware designers in the field
  70. of magnetic recording.  Programming has been a hobby of his off
  71. and on since 1968 when he learned how to keypunch cards for
  72. submission to be run on a mainframe.  (The mainframe had 64K of
  73. magnetic core memory!).
  74.  
  75. Use of this Material:
  76.  
  77.     Everything contained herein is hereby released to the Public
  78. Domain.  Any person may copy or distribute this material in any
  79. manner they wish.  The only thing I ask is that if this material
  80. is used as a teaching aid in a class, I would appreciate it if it
  81. were distributed in its entirety, i.e. including all chapters,
  82. the preface and the introduction.  I would also appreciate it if
  83. under such circumstances the instructor of such a class would
  84. drop me a note at one of the addresses below informing me of
  85. this.  I have written this with the hope that it will be useful
  86. to others and since I'm not asking any financial remuneration,
  87. the only way I know that I have at least partially reached that
  88. goal is via feedback from those who find this material useful.
  89.  
  90.     By the way, you needn't be an instructor or teacher to
  91. contact me.  I would appreciate a note from _anyone_ who finds
  92. the material useful, or who has constructive criticism to offer.
  93. I'm also willing to answer questions submitted by mail.
  94.  
  95. Ted Jensen                        tjensen@netcom.com
  96. P.O. Box 324                      1-415-365-8452
  97. Redwood City, CA 94064
  98. Dec. 1995
  99.  
  100. ->============================================================
  101. INTRODUCTION
  102.  
  103.     If one is to be proficient in the writing of code in the C
  104. programming language, one must have a thorough working knowledge
  105. of how to use pointers.  Unfortunately, C pointers appear to
  106. represent a stumbling block to newcomers, particularly those
  107. coming from other computer languages such as Fortran, Pascal or
  108. Basic.
  109.  
  110.     To aid those newcomers in the understanding of pointers I have
  111. written the following material.  To get the maximum benefit from
  112. this material, I feel it is important that the user be able to
  113. run the code in the various listings contained in the article.  I
  114. have attempted, therefore, to keep all code ANSI compliant so
  115. that it will work with any ANSI compliant compiler.  And I have
  116. tried to carefully block the code within the text so that with
  117. the help of an ASCII text editor one can copy a given block of
  118. code to a new file and compile it on their system.  I recommend
  119. that readers do this as it will help in understanding the
  120. material.
  121.  
  122.  
  123.  
  124. ->==================================================================
  125. CHAPTER 1: What is a pointer?
  126.  
  127.     One of the things beginners in C find most difficult to
  128. understand is the concept of pointers.  The purpose of this
  129. document is to provide an introduction to pointers and their use
  130. to these beginners.
  131.  
  132.     I have found that often the main reason beginners have a
  133. problem with pointers is that they have a weak or minimal feeling
  134. for variables, (as they are used in C).  Thus we start with a
  135. discussion of C variables in general.
  136.  
  137.     A variable in a program is something with a name, the value
  138. of which can vary.  The way the compiler and linker handles this
  139. is that it assigns a specific block of memory within the computer
  140. to hold the value of that variable.  The size of that block
  141. depends on the range over which the variable is allowed to vary.
  142. For example, on PC's the size of an integer variable is 2 bytes,
  143. and that of a long integer is 4 bytes.  In C the size of a
  144. variable type such as an integer need not be the same on all
  145. types of machines.
  146.  
  147.     When we declare a variable we inform the compiler of two
  148. things, the name of the variable and the type of the variable.
  149. For example, we declare a variable of type integer with the name
  150. k by writing:
  151.  
  152.     int k;
  153.  
  154.     On seeing the "int" part of this statement the compiler sets
  155. aside 2 bytes (on a PC) of memory to hold the value of the
  156. integer.  It also sets up a symbol table. And in that table it
  157. adds the symbol k and the relative address in memory where those
  158. 2 bytes were set aside.
  159.  
  160.     Thus, later if we write:
  161.  
  162.     k = 2;
  163.  
  164. at run time we expect that the value 2 will be placed in that
  165. memory location reserved for the storage of the value of k.  In C
  166. we refer to a variable such as the integer k as an "object".
  167.  
  168.     In a sense there are two "values" associated with the object
  169. k, one being the value of the integer stored there (2 in the
  170. above example) and the other being the "value" of the memory
  171. location where it is stored, i.e. the address of k.  Some texts
  172. refer to these two values with the nomenclature rvalue (right
  173. value, pronounced "are value") and lvalue (left value, pronounced
  174. "el value") respectively.
  175.  
  176.     In some languages, the lvalue is the value permitted on the
  177. left side of the assignment operator '=' (i.e. the address where
  178. the result of evaluation of the right side ends up).  The rvalue
  179. is that which is on the right side of the assignment statement,
  180. the '2' above.  Rvalues cannot be used on the left side
  181. of the assignment statement.  Thus:    2 = k;   is illegal.
  182.  
  183.     However, the above definition of "lvalue" is somewhat
  184. modified for C to be..
  185.  
  186.      An _object_ is a region of storage; an _lvalue_ is an
  187.      expression referring to an object.
  188.  
  189. As we become more familiar with pointers we will go into more
  190. detail on this.
  191.  
  192.     Okay, now consider:
  193.  
  194.     int j, k;
  195.     k = 2;
  196.     j = 7;    <-- line 1
  197.     k = j;    <-- line 2
  198.  
  199.     In the above, the compiler interprets the j in line 1 as the
  200. address of the variable j (its lvalue) and creates code to copy
  201. the value 7 to that address.  In line 2, however, the j is
  202. interpreted as its rvalue (since it is on the right hand side of
  203. the assignment operator '=').  That is, here the j refers to the
  204. value _stored_ at the memory location set aside for j, in this
  205. case 7.  So, the 7 is copied to the address designated by the
  206. lvalue of k.
  207.  
  208.     In all of these examples, we are using 2 byte integers so all
  209. copying of rvalues from one storage location to the other is done
  210. by copying 2 bytes.  Had we been using long integers, we would be
  211. copying 4 bytes.
  212.  
  213.     Now, let's say that we have a reason for wanting a variable
  214. designed to hold an lvalue (an address).  The size required to
  215. hold such a value depends on the system.  On older desk top
  216. computers with 64K of memory total, the address of any point in
  217. memory can be contained in 2 bytes.  Computers with more memory
  218. would require more bytes to hold an address.  Some computers,
  219. such as the IBM PC might require special handling to hold a
  220. segment and offset under certain circumstances.  The actual size
  221. required is not too important so long as we have a way of
  222. informing the compiler that what we want to store is an address.
  223.  
  224.     Such a variable is called a "pointer variable" (for reasons
  225. which hopefully will become clearer a little later).  In C when
  226. we define a pointer variable we do so by preceding its name with
  227. an asterisk.  In C we also give our pointer a type which, in this
  228. case, refers to the type of data stored at the address we will be
  229. storing in our pointer.  For example, consider the variable
  230. declaration:
  231.  
  232.     int *ptr;
  233.  
  234.     ptr is the _name_ of our variable (just as 'k' was the name
  235. of our integer variable).  The '*' informs the compiler that we
  236. want a pointer variable, i.e. to set aside however many bytes is
  237. required to store an address in memory.  The "int" says that we
  238. intend to use our pointer variable to store the address of an
  239. integer. Such a pointer is said to "point to" an integer.
  240. However, note that when we wrote  "int k;" we did not give k a value.
  241. If this definition was made outside of any function many compilers
  242. will initialize it to zero.  Similarly, ptr has no value, that is
  243. we haven't stored an address in it in the above declaration.  In
  244. this case, again if the declaration is outside of any function,
  245. it is initialized to a value #defined by your compiler as NULL. It
  246. is called a NULL pointer.  While in most cases NULL is #defined
  247. as zero, it need not be.  That is, different compilers handle
  248. this differently.  Also while zero is an integer, NULL
  249. need not be.  However, the value that NULL actually has
  250. internally is of little consequence to the programmer since at
  251. the source code level   NULL == 0  is guaranteed to evaluate to
  252. true regardless of the internal value of NULL.
  253.  
  254.     But, back to using our new variable ptr.  Suppose now that we
  255. want to store in ptr the address of our integer variable k.  To
  256. do this we use the unary '&' operator and write:
  257.  
  258.     ptr = &k;
  259.  
  260.     What the '&' operator does is retrieve the address
  261. of k, even though k is on the right hand side of the assignment
  262. operator '=', and copies that to the contents of our pointer ptr.
  263. Now, ptr is said to "point to" k.  Bear with us now, there is
  264. only one more operator we need to discuss.
  265.  
  266.     The "dereferencing operator" is the asterisk and it is used
  267. as follows:
  268.  
  269.     *ptr = 7;
  270.  
  271. will copy 7 to the address pointed to by ptr.  Thus if ptr
  272. "points to" (contains the address of) k, the above statement will
  273. set the value of k to 7.  That is, when we use the '*' this way
  274. we are referring to the value of that which ptr is pointing
  275. to, not the value of the pointer itself.
  276.  
  277.     Similarly, we could write:
  278.  
  279.     printf("%d\n",*ptr);
  280.  
  281. to print to the screen the integer value stored at the address
  282. pointed to by "ptr".
  283.  
  284.     One way to see how all this stuff fits together would be to
  285. run the following program and then review the code and the output
  286. carefully.
  287.  
  288. ------------ Program 1.1 ---------------------------------
  289.  
  290. /* Program 1.1 from PTRTUT02.TXT   12/14/95 */
  291.  
  292. #include <stdio.h>
  293.  
  294. int j, k;
  295. int *ptr;
  296.  
  297.  
  298. int main(void)
  299. {
  300.    j = 1;
  301.    k = 2;
  302.    ptr = &k;
  303.    printf("\n");
  304.    printf("j has the value %d and is stored at %p\n",j,&j);
  305.    printf("k has the value %d and is stored at %p\n",k,&k);
  306.    printf("ptr has the value %p and is stored at %p\n",ptr,&ptr);
  307.    printf("The value of the integer pointed to by ptr is %d\n",
  308.            *ptr);
  309.    return 0;
  310. }
  311. ---------------------------------------
  312. To review:
  313.  
  314.     A variable is declared by giving it a type and a name (e.g.
  315.      int k;)
  316.  
  317.     A pointer variable is declared by giving it a type and a name
  318.      (e.g. int *ptr) where the asterisk tells the compiler that
  319.      the variable named ptr is a pointer variable and the type
  320.      tells the compiler what type the pointer is to point to
  321.      (integer in this case).
  322.  
  323.     Once a variable is declared, we can get its address by
  324.      preceding its name with the unary '&' operator, as in &k.
  325.  
  326.     We can "dereference" a pointer, i.e. refer to the value of
  327.      that which it points to, by using the unary '*' operator as
  328.      in *ptr.
  329.  
  330.     An "lvalue" of a variable is the value of its address, i.e.
  331.      where it is stored in memory.  The "rvalue" of a variable is
  332.      the value stored in that variable (at that address).
  333.  
  334. References in Chapter 1:
  335.  
  336.     [1]  "The C Programming Language"   2nd Edition
  337.           B. Kernighan and D. Ritchie
  338.           Prentice Hall
  339.           ISBN 0-13-110362-8
  340.  
  341. ->==================================================================
  342. CHAPTER 2: Pointer types and Arrays
  343.  
  344.     Okay, let's move on.  Let us consider why we need to identify
  345. the "type" of variable that a pointer points to, as in:
  346.  
  347.         int *ptr;
  348.  
  349.     One reason for doing this is so that later, once ptr "points
  350. to" something, if we write:
  351.  
  352.         *ptr = 2;
  353.  
  354. the compiler will know how many bytes to copy into that memory
  355. location pointed to by ptr.  If ptr was declared as pointing to an
  356. integer, 2 bytes would be copied, if a long, 4 bytes would be
  357. copied.  Similarly for floats and doubles the appropriate number
  358. will be copied.  But, defining the type that the pointer points
  359. to permits a number of other interesting ways a compiler can
  360. interpret code.  For example, consider a block in memory
  361. consisting if ten integers in a row.  That is, 20 bytes of memory
  362. are set aside to hold 10 integers.
  363.  
  364.     Now, let's say we point our integer pointer ptr at the first
  365. of these integers.  Furthermore lets say that integer is located
  366. at memory location 100 (decimal).  What happens when we write:
  367.  
  368.     ptr + 1;
  369.  
  370.     Because the compiler "knows" this is a pointer (i.e. its
  371. value is an address) and that it points to an integer (its
  372. current address, 100, is the address of an integer), it adds 2 to
  373. ptr instead of 1, so the pointer "points to" the _next_
  374. _integer_, at memory location 102.  Similarly, were the ptr
  375. declared as a pointer to a long, it would add 4 to it instead of
  376. 1.  The same goes for other data types such as floats, doubles,
  377. or even user defined data types such as structures.  This is
  378. obviously not the same kind of "addition" that we normally think
  379. of.  In C it is referred to as addition using "pointer
  380. arithmetic", a term which we will come back to later.
  381.  
  382.     Similarly, since ++ptr and ptr++ are both equivalent to
  383. ptr + 1 (though the point in the program when ptr is incremented
  384. may be different), incrementing a pointer using the unary ++
  385. operator, either pre- or post-, increments the address it stores
  386. by the amount sizeof(type) where "type" is the type of the object
  387. pointed to. (i.e. 2 for an integer, 4 for a long,
  388. etc.).
  389.  
  390.     Since a block of 10 integers located contiguously in memory
  391. is, by definition, an array of integers, this brings up an
  392. interesting relationship between arrays and pointers.
  393.  
  394.     Consider the following:
  395.  
  396.     int my_array[] = {1,23,17,4,-5,100};
  397.  
  398.     Here we have an array containing 6 integers.  We refer to
  399. each of these integers by means of a subscript to my_array, i.e.
  400. using my_array[0] through my_array[5].  But, we could
  401. alternatively access them via a pointer as follows:
  402.  
  403.     int *ptr;
  404.  
  405.     ptr = &my_array[0];       /* point our pointer at the first
  406.                                  integer in our array */
  407.  
  408.     And then we could print out our array either using the array
  409. notation or by dereferencing our pointer.  The following code
  410. illustrates this:
  411. -----------  Program 2.1  -----------------------------------
  412. /* Program 2.1 from PTRTUT02.TXT   12/14/95 */
  413.  
  414.  
  415. #include <stdio.h>
  416.  
  417. int my_array[] = {1,23,17,4,-5,100};
  418. int *ptr;
  419.  
  420. int main(void)
  421. {
  422.     int i;
  423.     ptr = &my_array[0];     /* point our pointer to the first
  424.                                       element of the array */
  425.     printf("\n\n");
  426.     for(i = 0; i < 6; i++)
  427.     {
  428.       printf("my_array[%d] = %d   ",i,my_array[i]);   /*<-- A */
  429.       printf("ptr + %d = %d\n",i, *(ptr + i));        /*<-- B */
  430.     }
  431.     return 0;
  432. }
  433. ----------------------------------------------------
  434.    Compile and run the above program and carefully note lines A
  435. and B and that the program prints out the same values in either
  436. case.  Also observe how we dereferenced our pointer in line B,
  437. i.e. we first added i to it and then dereferenced the new
  438. pointer. Change line B to read:
  439.  
  440.      printf("ptr + %d = %d\n",i, *ptr++);
  441.  
  442. and run it again... then change it to:
  443.  
  444.      printf("ptr + %d = %d\n",i, *(++ptr));
  445.  
  446. and try once more.  Each time try and predict the outcome and
  447. carefully look at the actual outcome.
  448.  
  449.     In C, the standard states that wherever we might use
  450. &var_name[0] we can replace that with var_name, thus in our code
  451. where we wrote:
  452.  
  453.         ptr = &my_array[0];
  454.  
  455.     we can write:
  456.  
  457.         ptr = my_array;     to achieve the same result.
  458.  
  459.     This leads many texts to state that the name of an array is a
  460. pointer.  While this is true, I prefer to mentally think "the
  461. name of the array is the address of first element in the array".
  462. Many beginners (including myself when I was learning) have a
  463. tendency to become confused by thinking of it as a pointer.
  464. For example, while we can write ptr = my_array; we cannot write
  465.  
  466.     my_array = ptr;
  467.  
  468.     The reason is that the while ptr is a variable, my_array is a
  469. constant.  That is, the location at which the first element of
  470. my_array will be stored cannot be changed once my_array[] has
  471. been declared.
  472.  
  473.     Earlier when discussing the term "lvalue" I stated that
  474.  
  475.     "An _object_ is a region of storage; an _lvalue_ is an
  476.      expression referring to an object".
  477.  
  478. This raises an interesting problem.  Since my_array is a named
  479. region of storage, why is "my_array" in the above assignment
  480. statement not an lvalue?  To resolve this problem, some refer to
  481. "my_array" as an "unmodifiable lvalue".
  482.  
  483. Modify the example program above by changing
  484.  
  485.     ptr = &my_array[0];     to     ptr = my_array;
  486.  
  487. and run it again to verify the results are identical.
  488.  
  489.     Now, let's delve a little further into the difference between
  490. the names "ptr" and "my_array" as used above.  Some writers will
  491. refer to an array's name as a _constant_ pointer.  What do we
  492. mean by that?  Well, to understand the term "constant" in this
  493. sense, let's go back to our definition of the term "variable".
  494. When we declare a variable we set aside a spot in memory to hold
  495. the value of the appropriate type.  Once that is done the name of
  496. the variable can be interpreted in one of two ways.  When used on
  497. the left side of the assignment operator, the compiler interprets
  498. it as the memory location to which to move that value resulting
  499. from evaluation of the right side of the assignment operator.
  500. But, when used on the right side of the assignment operator, the
  501. name of a variable is interpreted to mean the contents stored at
  502. that memory address set aside to hold the value of that variable.
  503.  
  504.     With that in mind, let's now consider the simplest of
  505. constants, as in:
  506.  
  507.     int i, k;
  508.     i = 2;
  509.  
  510.     Here, while "i" is a variable and then occupies space in the
  511. data portion of memory, "2" is a constant and, as such, instead
  512. of setting aside memory in the data segment, it is imbedded
  513. directly in the code segment of memory.  That is, while writing
  514. something like k = i;  tells the compiler to create code which at
  515. run time will look at memory location &i to determine the value
  516. to be moved to k, code created by  i = 2;  simply puts the '2' in
  517. the code and there is no referencing of the data segment.  That
  518. is, both k and i are objects, but 2 is not an object.
  519.  
  520.     Similarly, in the above, since "my_array" is a constant, once
  521. the compiler establishes where the array itself is to be stored,
  522. it "knows" the address of my_array[0] and on seeing:
  523.  
  524.     ptr = my_array;
  525.  
  526. it simply uses this address as a constant in the code segment and
  527. there is no referencing of the data segment beyond that.
  528.  
  529.     Well, that's a lot of technical stuff to digest and I don't
  530. expect a beginner to understand all of it on first reading.  With
  531. time and experimentation you will want to come back and re-read
  532. the first 2 chapters.  But for now, let's move on to the
  533. relationship between pointers, character arrays, and strings.
  534.  
  535. ->==================================================================
  536. CHAPTER 3:  Pointers and Strings
  537.  
  538.     The study of strings is useful to further tie in the
  539. relationship between pointers and arrays.  It also makes it easy
  540. to illustrate how some of the standard C string functions can be
  541. implemented. Finally it illustrates how and when pointers can and
  542. should be passed to functions.
  543.  
  544.     In C, strings are arrays of characters.  This is not
  545. necessarily true in other languages.  In BASIC, Pascal, Fortran
  546. and various other languages, a string has its own data type.  But
  547. in C it does not.  In C a string is an array of characters
  548. terminated with a binary zero character (written as '\0'). To
  549. start off our discussion we will write some code which, while
  550. preferred for illustrative purposes, you would probably never
  551. write in an actual program.  Consider, for example:
  552.  
  553.     char my_string[40];
  554.  
  555.     my_string[0] = 'T';
  556.     my_string[1] = 'e';
  557.     my_string[2] = 'd':
  558.     my_string[3] = '\0';
  559.  
  560.     While one would never build a string like this, the end
  561. result is a string in that it is an array of characters
  562. _terminated_with_a_nul_character_.  By definition, in C, a string
  563. is an array of characters terminated with the nul character. Be
  564. aware that "nul" is _not_ the same as "NULL".  The nul refers to a zero
  565. as is defined by the escape sequence '\0'.  That is it occupies
  566. one byte of memory.  The NULL, on the other hand, is the value of
  567. an uninitialized pointer and pointers require more than one byte
  568. of storage.  NULL is #defined in a header file in your C
  569. compiler, nul may not be #defined at all.
  570.  
  571.     Since writing the above code would be very time consuming, C
  572. permits two alternate ways of achieving the same thing.  First,
  573. one might write:
  574.  
  575.     char my_string[40] = {'T', 'e', 'd', '\0',};
  576.  
  577.     But this also takes more typing than is convenient.  So, C
  578. permits:
  579.  
  580.     char my_string[40] = "Ted";
  581.  
  582.     When the double quotes are used, instead of the single quotes
  583. as was done in the previous examples, the nul character ( '\0' )
  584. is automatically appended to the end of the string.
  585.  
  586.     In all of the above cases, the same thing happens.  The
  587. compiler sets aside an contiguous block of memory 40 bytes long
  588. to hold characters and initialized it such that the first 4
  589. characters are Ted\0.
  590.  
  591.     Now, consider the following program:
  592.  
  593. ------------------program 3.1-------------------------------------
  594. /* Program 3.1 from PTRTUT02.TXT   12/14/95 */
  595.  
  596.  
  597. #include <stdio.h>
  598.  
  599. char strA[80] = "A string to be used for demonstration purposes";
  600. char strB[80];
  601.  
  602. int main(void)
  603. {
  604.    char *pA;     /* a pointer to type character */
  605.    char *pB;     /* another pointer to type character */
  606.    puts(strA);   /* show string A */
  607.    pA = strA;    /* point pA at string A */
  608.    puts(pA);     /* show what pA is pointing to */
  609.    pB = strB;    /* point pB at string B */
  610.    putchar('\n');       /* move down one line on the screen */
  611.    while(*pA != '\0')   /* line A (see text) */
  612.    {
  613.      *pB++ = *pA++;     /* line B (see text) */
  614.    }
  615.    *pB = '\0';          /* line C (see text) */
  616.    puts(strB);          /* show strB on screen */
  617.    return 0;
  618. }
  619. --------- end program 3.1 -------------------------------------
  620.  
  621.     In the above we start out by defining two character arrays of
  622. 80 characters each.  Since these are globally defined, they are
  623. initialized to all '\0's first.  Then, strA has the first 42
  624. characters initialized to the string in quotes.
  625.  
  626.     Now, moving into the code, we declare two character pointers
  627. and show the string on the screen.  We then "point" the pointer pA
  628. at strA.  That is, by means of the assignment statement we copy
  629. the address of strA[0] into our variable pA.  We now use puts()
  630. to show that which is pointed to by pA on the screen.  Consider
  631. here that the function prototype for puts() is:
  632.  
  633.     int puts(const char *s);
  634.  
  635.     For the moment, ignore the "const".  The parameter passed to
  636. puts is a pointer, that is the _value_ of a pointer (since all
  637. parameters in C are passed by value), and the value of a pointer
  638. is the address to which it points, or, simply, an address.  Thus
  639. when we write:
  640.  
  641.     puts(strA);        as we have seen, we are passing the
  642.  
  643. address of strA[0].  Similarly, when we write:
  644.  
  645.     puts(pA);          we are passing the same address, since
  646.  
  647. we have set pA = strA;
  648.  
  649.     Given that, follow the code down to the while() statement on
  650. line A.  Line A states:
  651.  
  652.     While the character pointed to by pA (i.e. *pA) is not a nul
  653. character (i.e. the terminating '\0'), do the following:
  654.  
  655.     line B states:  copy the character pointed to by pA to the
  656. space pointed to by pB, then increment pA so it points to the
  657. next character and pB so it points to the next space.
  658.  
  659.     When we have copied the last character, pA now points to the
  660. terminating nul character and the loop ends. However, we have not
  661. copied the nul character.  And, by definition a string in C
  662. _must_ be nul terminated.  So, we add the nul character with line
  663. C.
  664.  
  665.     It is very educational to run this program with your debugger
  666. while watching strA, strB, pA and pB and single stepping through
  667. the program.  It is even more educational if instead of simply
  668. defining strB[] as has been done above, initialize it also with
  669. something like:
  670.  
  671.  strB[80] = "12345678901234567890123456789012345678901234567890"
  672.  
  673. where the number of digits used is greater than the length of
  674. strA and then repeat the single stepping procedure while watching
  675. the above variables.  Give these things a try!
  676.  
  677.     Getting back to the prototype for puts() for a moment, the
  678. "const" used as a parameter modifier informs the user that the
  679. function will not modify the string pointed to by s, i.e. it will
  680. treat that string as a constant.
  681.  
  682.     Of course, what the above program illustrates is a simple way
  683. of copying a string.  After playing with the above until you have
  684. a good understanding of what is happening, we can proceed to
  685. creating our own replacement for the standard strcpy() that comes
  686. with C.  It might look like:
  687.  
  688.    char *my_strcpy(char *destination, char *source)
  689.    {
  690.         char *p = destination;
  691.         while (*source != '\0')
  692.         {
  693.            *p++ = *source++;
  694.         }
  695.         *p = '\0';
  696.         return destination;
  697.    }
  698.  
  699.     In this case, I have followed the practice used in the
  700. standard routine of returning a pointer to the destination.
  701.  
  702.     Again, the function is designed to accept the values of two
  703. character pointers, i.e. addresses, and thus in the previous
  704. program we could write:
  705.  
  706. int main(void)
  707. {
  708.   my_strcpy(strB, strA);
  709.   puts(strB);
  710. }
  711.  
  712.     I have deviated slightly from the form used in standard C
  713. which would have the prototype:
  714.  
  715.     char *my_strcpy(char *destination, const char *source);
  716.  
  717.     Here the "const" modifier is used to assure the user that the
  718. function will not modify the contents pointed to by the source
  719. pointer.  You can prove this by modifying the function above, and
  720. its prototype, to include the "const" modifier as shown.  Then,
  721. within the function you can add a statement which attempts to
  722. change the contents of that which is pointed to by source, such
  723. as:
  724.  
  725.     *source = 'X';
  726.  
  727. which would normally change the first character of the string to
  728. an X.  The const modifier should cause your compiler to catch
  729. this as an error.  Try it and see.
  730.  
  731.     Now, let's consider some of the things the above examples
  732. have shown us.  First off, consider the fact that *ptr++ is to be
  733. interpreted as returning the value pointed to by ptr and then
  734. incrementing the pointer value.  This has to
  735. do with the precedence of the operators.  Were we to write
  736. (*ptr)++ we would increment, not the pointer, but that which the
  737. pointer points to!  i.e. if used on the first character of the
  738. above example string the 'T' would be incremented to a 'U'.  You
  739. can write some simple example code to illustrate this.
  740.  
  741.     Recall again that a string is nothing more than an array
  742. of characters, with the last character being a '\0'.  What we
  743. have done above is deal with copying an array.  It happens to be
  744. an array of characters but the technique could be applied to an
  745. array of integers, doubles, etc.  In those cases, however, we
  746. would not be dealing with strings and hence the end of the array
  747. would not be marked with a special value like the nul character.
  748. We could implement a version that relied on a special value to
  749. identify the end. For example, we could copy an array of positive
  750. integers by marking the end with a negative integer.  On the
  751. other hand, it is more usual that when we write a function to
  752. copy an array of items other than strings we pass the function
  753. the number of items to be copied as well as the address of the
  754. array, e.g. something like the following prototype might
  755. indicate:
  756.  
  757.     void int_copy(int *ptrA, int *ptrB, int nbr);
  758.  
  759. where nbr is the number of integers to be copied.  You might want
  760. to play with this idea and create an array of integers and see if
  761. you can write the function int_copy() and make it work.
  762.  
  763.     This permits using functions to manipulate large arrays. For
  764. example, if we have an array of 5000 integers that we want to
  765. manipulate with a function, we need only pass to that function
  766. the address of the array (and any auxiliary information such as
  767. nbr above, depending on what we are doing). The array itself does
  768. _not_ get passed, i.e. the whole array is not copied and put on
  769. the stack before calling the function, only its address is sent.
  770.  
  771.     This is different from passing, say an integer, to a
  772. function.  When we pass an integer we make a copy of the integer,
  773. i.e. get its value and put it on the stack.  Within the function
  774. any manipulation of the value passed can in no way effect the
  775. original integer.  But, with arrays and pointers we can pass the
  776. address of the variable and hence manipulate the values of the
  777. original variables.
  778.  
  779. ->==================================================================
  780. CHAPTER 4: More on Strings
  781.  
  782.     Well, we have progressed quite a way in a short time!  Let's
  783. back up a little and look at what was done in Chapter 3 on
  784. copying of strings but in a different light.  Consider the
  785. following function:
  786.  
  787.    char *my_strcpy(char dest[], char source[])
  788.    {
  789.         int i = 0;
  790.  
  791.         while (source[i] != '\0')
  792.         {
  793.            dest[i] = source[i];
  794.            i++;
  795.         }
  796.         dest[i] = '\0';
  797.         return dest;
  798.    }
  799.  
  800.     Recall that strings are arrays of characters.  Here we have
  801. chosen to use array notation instead of pointer notation to do
  802. the actual copying.  The results are the same, i.e. the string
  803. gets copied using this notation just as accurately as it did
  804. before.  This raises some interesting points which we will
  805. discuss.
  806.  
  807.     Since parameters are passed by value, in both the passing of
  808. a character pointer or the name of the array as above, what
  809. actually gets passed is the address of the first element of each
  810. array.  Thus, the numerical value of the parameter passed is the
  811. same whether we use a character pointer or an array name as a
  812. parameter.  This would tend to imply that somehow:
  813.  
  814.         source[i]  is the same as  *(p+i);
  815.  
  816.     In fact, this is true, i.e wherever one writes   a[i]  it can
  817. be replaced with  *(a + i) without any problems.  In fact, the
  818. compiler will create the same code in either case.  Thus we see
  819. that pointer arithmetic is the same thing as array indexing.
  820. Either syntax produces the same result.
  821.  
  822.     This is NOT saying that pointers and arrays are the same
  823. thing, they are not.  We are only saying that to identify a given
  824. element of an array we have the choice of two syntaxes, one using
  825. array indexing and the other using pointer arithmetic, which
  826. yield identical results.
  827.  
  828.     Now, looking at this last expression, part of it..  (a + i)
  829. is a simple addition using the + operator and the rules of c
  830. state that such an expression is commutative.  That is   (a + i)
  831. is identical to (i + a).  Thus we could write *(i + a) just as
  832. easily as *(a + i).
  833.  
  834.     But *(i + a) could have come from i[a] !  From all of this
  835. comes the curious truth that if:
  836.  
  837.     char a[20];
  838.     int i;
  839.  
  840.     writing    a[3] = 'x';   is the same as writing
  841.  
  842.                3[a] = 'x';
  843.  
  844.     Try it!  Set up an array of characters, integers or longs,
  845. etc. and assigned the 3rd or 4th element a value using the
  846. conventional approach and then print out that value to be sure
  847. you have that working.  Then reverse the array notation as I have
  848. done above.  A good compiler will not balk and the results will
  849. be identical.  A curiosity... nothing more!
  850.  
  851.     Now, looking at our function above, when we write:
  852.  
  853.         dest[i] = source[i];
  854.  
  855. due to the fact that array indexing and pointer arithmetic yield
  856. identical results, we can write this as:
  857.  
  858.         *(dest + i) = *(source + i);
  859.  
  860.     But, this takes 2 additions for each value taken on by i.
  861. Additions, generally speaking, take more time than
  862. incrementations (such as those done using the ++ operator as in
  863. i++).  This may not be true in modern optimizing compilers, but
  864. one can never be sure.  Thus, the pointer version may be a bit
  865. faster than the array version.
  866.  
  867.     Another way to speed up the pointer version would be to
  868. change:
  869.  
  870.     while (*source != '\0')     to simply    while (*source)
  871.  
  872. since the value within the parenthesis will go to zero (FALSE) at
  873. the same time in either case.
  874.  
  875.     At this point you might want to experiment a bit with writing
  876. some of your own programs using pointers.  Manipulating strings
  877. is a good place to experiment.  You might want to write your own
  878. versions of such standard functions as:
  879.  
  880.             strlen();
  881.             strcat();
  882.             strchr();
  883.  
  884. and any others you might have on your system.
  885.  
  886.     We will come back to strings and their manipulation through
  887. pointers in a future chapter.  For now, let's move on and discuss
  888. structures for a bit.
  889.  
  890. ->==================================================================
  891. CHAPTER 5: Pointers and Structures
  892.  
  893.     As you may know, we can declare the form of a block of data
  894. containing different data types by means of a structure
  895. declaration.  For example, a personnel file might contain
  896. structures which look something like:
  897.  
  898.   struct tag{
  899.        char lname[20];        /* last name */
  900.        char fname[20];        /* first name */
  901.        int age;               /* age */
  902.        float rate;            /* e.g. 12.75 per hour */
  903.        };
  904.  
  905.     Let's say we have a bunch of these structures in a disk file
  906. and we want to read each one out and print out the first and last
  907. name of each one so that we can have a list of the people in our
  908. files.  The remaining information will not be printed out.  We
  909. will want to do this printing with a function call and pass to
  910. that function a pointer to the structure at hand.  For
  911. demonstration purposes I will use only one structure for now. But
  912. realize the goal is the writing of the function, not the reading
  913. of the file which, presumably, we know how to do.
  914.  
  915.     For review, recall that we can access structure members with
  916. the dot operator as in:
  917.  
  918. --------------- program 5.1 ------------------
  919. /* Program 5.1 from PTRTUT02.TXT   12/14/95 */
  920.  
  921. #include <stdio.h>
  922. #include <string.h>
  923.  
  924. struct tag{
  925.        char lname[20];      /* last name */
  926.        char fname[20];      /* first name */
  927.        int age;             /* age */
  928.        float rate;          /* e.g. 12.75 per hour */
  929.        };
  930.  
  931. struct tag my_struct;       /* declare the structure my_struct */
  932.  
  933. int main(void)
  934. {
  935.   strcpy(my_struct.lname,"Jensen");
  936.   strcpy(my_struct.fname,"Ted");
  937.   printf("\n%s ",my_struct.fname);
  938.   printf("%s\n",my_struct.lname);
  939.   return 0;
  940. }
  941. -------------- end of program 5.1 --------------
  942.  
  943.     Now, this particular structure is rather small compared to
  944. many used in C programs.  To the above we might want to add:
  945.  
  946.   date_of_hire;                  (data types not shown)
  947.   date_of_last_raise;
  948.   last_percent_increase;
  949.   emergency_phone;
  950.   medical_plan;
  951.   Social_S_Nbr;
  952.   etc.....
  953.  
  954.     If we have a large number of employees, what we want to do
  955. manipulate the data in these structures by means of functions.
  956. For example we might want a function print out the name of the
  957. employee listed in any structure passed to it.  However, in the
  958. original C (Kernighan & Ritchie, 1st Edition) it was not possible
  959. to pass a structure, only a pointer to a structure could be
  960. passed.  In ANSI C, it is now permissible to pass the complete
  961. structure. But, since our goal here is to learn more about
  962. pointers, we won't pursue that.
  963.  
  964.     Anyway, if we pass the whole structure it means that we must
  965. copy the contents of the structure from the calling function to
  966. the called function.  In systems using stacks, this is done by
  967. pushing the contents of the structure on the stack.  With large
  968. structures this could prove to be a problem.  However, passing a
  969. pointer uses a minimum amount of stack space.
  970.  
  971.     In any case, since this is a discussion of pointers, we will
  972. discuss how we go about passing a pointer to a structure and then
  973. using it within the function.
  974.  
  975.     Consider the case described, i.e. we want a function that
  976. will accept as a parameter a pointer to a structure and from
  977. within that function we want to access members of the structure.
  978. For example we want to print out the name of the employee in our
  979. example structure.
  980.  
  981.     Okay, so we know that our pointer is going to point to a
  982. structure declared using struct tag.  We declare such a pointer
  983. with the declaration:
  984.  
  985.     struct tag *st_ptr;
  986.  
  987. and we point it to our example structure with:
  988.  
  989.     st_ptr = &my_struct;
  990.  
  991.     Now, we can access a given member by de-referencing the
  992. pointer. But, how do we de-reference the pointer to a structure?
  993. Well, consider the fact that we might want to use the pointer to
  994. set the age of the employee.  We would write:
  995.  
  996.     (*st_ptr).age = 63;
  997.  
  998.     Look at this carefully.  It says, replace that within the
  999. parenthesis with that which st_ptr points to, which is the
  1000. structure my_struct.  Thus, this breaks down to the same as
  1001. my_struct.age.
  1002.  
  1003.     However, this is a fairly often used expression and the
  1004. designers of C have created an alternate syntax with the same
  1005. meaning which is:
  1006.  
  1007.     st_ptr->age = 63;
  1008.  
  1009.     With that in mind, look at the following program:
  1010.  
  1011. ------------ program 5.2 ---------------------
  1012. /* Program 5.2 from PTRTUT02.TXT   12/14/95 */
  1013.  
  1014. #include <stdio.h>
  1015. #include <string.h>
  1016.  
  1017. struct tag{                   /* the structure type */
  1018.        char lname[20];        /* last name */
  1019.        char fname[20];        /* first name */
  1020.        int age;               /* age */
  1021.        float rate;            /* e.g. 12.75 per hour */
  1022.        };
  1023.  
  1024. struct tag my_struct;         /* define the structure */
  1025.  
  1026. void show_name(struct tag *p);    /* function prototype */
  1027.  
  1028. int main(void)
  1029. {
  1030.   struct tag *st_ptr;         /* a pointer to a structure */
  1031.   st_ptr = &my_struct;        /* point the pointer to my_struct */
  1032.   strcpy(my_struct.lname,"Jensen");
  1033.   strcpy(my_struct.fname,"Ted");
  1034.   printf("\n%s ",my_struct.fname);
  1035.   printf("%s\n",my_struct.lname);
  1036.   my_struct.age = 63;
  1037.   show_name(st_ptr);          /* pass the pointer */
  1038.   return 0;
  1039. }
  1040.  
  1041.  
  1042. void show_name(struct tag *p)
  1043. {
  1044.   printf("\n%s ", p->fname);     /* p points to a structure */
  1045.   printf("%s ", p->lname);
  1046.   printf("%d\n", p->age);
  1047. }
  1048. -------------------- end of program 5.2 ----------------
  1049.  
  1050.     Again, this is a lot of information to absorb at one time.
  1051. The reader should compile and run the various code snippets and
  1052. using a debugger monitor things like my_struct and p while single
  1053. stepping through the main and following the code down into the
  1054. function to see what is happening.
  1055.  
  1056. ->==================================================================
  1057. CHAPTER 6:  Some more on Strings, and Arrays of Strings
  1058.  
  1059.    Well, let's go back to strings for a bit.  In the following
  1060. all assignments are to be understood as being global, i.e. made
  1061. outside of any function, including main.
  1062.  
  1063.    We pointed out in an earlier chapter that we could write:
  1064.  
  1065.    char my_string[40] = "Ted";
  1066.  
  1067. which would allocate space for a 40 byte array and put the string
  1068. in the first 4 bytes (three for the characters in the quotes and
  1069. a 4th to handle the terminating '\0'.
  1070.  
  1071.     Actually, if all we wanted to do was store the name "Ted" we
  1072. could write:
  1073.  
  1074.       char my_name[] = "Ted";
  1075.  
  1076. and the compiler would count the characters, leave room for the
  1077. nul character and store the total of the four characters in memory
  1078. the location of which would be returned by the array name, in this
  1079. case my_string.
  1080.  
  1081.     In some code, instead of the above, you might see:
  1082.  
  1083.      char *my_name = "Ted";
  1084.  
  1085. which is an alternate approach.  Is there a difference between
  1086. these?  The answer is.. yes.  Using the array notation 4 bytes of
  1087. storage in the static memory block are taken up, one for each
  1088. character and one for the terminating nul character.  But, in the
  1089. pointer notation the same 4 bytes required, _plus_ N bytes to
  1090. store the pointer variable my_name (where N depends on the system
  1091. but is usually a minimum of 2 bytes and can be 4 or more).
  1092.  
  1093.     In the array notation, "my_name" is short for &myname[0]
  1094. which is the address of the first element of the array.  Since
  1095. the location of the array is fixed during run time, this is a
  1096. constant (not a variable).  In the pointer notation my_name is a
  1097. variable.  As to which is the _better_ method, that depends on
  1098. what you are going to do within the rest of the program.
  1099.  
  1100.     Let's now go one step further and consider what happens if
  1101. each of these declarations are done within a function as opposed
  1102. to globally outside the bounds of any function.
  1103.  
  1104. void my_function_A(char *ptr)
  1105. {
  1106.   char a[] = "ABCDE";
  1107.   .
  1108.   .
  1109. }
  1110.  
  1111. void my_function_B(char *ptr)
  1112. {
  1113.   char *cp = "ABCDE";
  1114.   .
  1115.   .
  1116. }
  1117.  
  1118.     Here we are dealing with automatic variables in both cases.
  1119. In my_function_A the automatic variable is the character array
  1120. a[]. In my_function_B it is the pointer cp.  While C is designed
  1121. in such a way that a stack is not required on those systems
  1122. which don't use them, my particular processor (80286) and
  1123. compiler (TC++) combination uses a stack.  I wrote a simple
  1124. program incorporating functions similar to those above and found
  1125. that in my_function_A the 5 characters in the string were all
  1126. stored on the stack.  On the other hand, in my_function_B, the 5
  1127. characters were stored in the data space and the pointer was
  1128. stored on the stack.
  1129.  
  1130.     By making a[] static I could force the compiler to place the
  1131. 5 characters in the data space as opposed to the stack.  I did
  1132. this exercise to point out just one more difference between
  1133. dealing with arrays and dealing with pointers.  By the way, array
  1134. initialization of automatic variables as I have done in
  1135. my_function_A was illegal in the older K&R C and only "came of
  1136. age" in the newer ANSI C.  A fact that may be important when one
  1137. is considering portability and backwards compatibility.
  1138.  
  1139.     As long as we are discussing the relationship/differences
  1140. between pointers and arrays, let's move on to multi-dimensional
  1141. arrays.  Consider, for example the array:
  1142.  
  1143.     char multi[5][10];
  1144.  
  1145.     Just what does this mean?   Well, let's consider it in the
  1146. following light.
  1147.  
  1148.         char multi[5][10];
  1149.              ^^^^^^^^
  1150.  
  1151.     Let's take the underlined part to be the "name" of an array.
  1152. Then prepending the "char" and appending the [10] we have an
  1153. array of 10 characters.  But, the name "multi[5]" is itself an
  1154. array indicating that there are 5 elements each being an array of
  1155. 10 characters.  Hence we have an array of 5 arrays of 10
  1156. characters each..
  1157.  
  1158.     Assume we have filled this two dimensional array with data of
  1159. some kind.  In memory, it might look as if it had been formed by
  1160. initializing 5 separate arrays using something like:
  1161.  
  1162.       multi[0] = {'0','1','2','3','4','5','6','7','8','9'}
  1163.       multi[1] = {'a','b','c','d','e','f','g','h','i','j'}
  1164.       multi[2] = {'A','B','C','D','E','F','G','H','I','J'}
  1165.       multi[3] = {'9','8','7','6','5','4','3','2','1','0'}
  1166.       multi[4] = {'J','I','H','G','F','E','D','C','B','A'}
  1167.  
  1168. At the same time, individual elements might be addressable using
  1169. syntax such as:
  1170.  
  1171.       multi[0][3] = '3'
  1172.       multi[1][7] = 'h'
  1173.       multi[4][0] = 'J'
  1174.  
  1175.     Since arrays are contiguous in memory, our actual memory
  1176. block for the above should look like:
  1177.  
  1178.     0123456789abcdefghijABCDEFGHIJ9876543210JIHGFEDCBA
  1179.     ^
  1180.     |_____ starting at the address &multi[0][0]
  1181.  
  1182.     Note that I did _not_ write  multi[0] = "0123456789". Had I
  1183. done so a terminating '\0' would have been implied since whenever
  1184. double quotes are used a '\0' character is appended to the
  1185. characters contained within those quotes.  Had that been the case
  1186. I would have had to set aside room for 11 characters per row
  1187. instead of 10.
  1188.  
  1189.     My goal in the above is to illustrate how memory is laid out
  1190. for 2 dimensional arrays. That is, this is a 2 dimensional array
  1191. of characters, NOT an array of "strings".
  1192.  
  1193.     Now, the compiler knows how many columns are present in the
  1194. array so it can interpret multi + 1 as the address of the 'a' in
  1195. the 2nd row above.  That is, it adds 10, the number of columns,
  1196. to get this location.  If we were dealing with integers and an
  1197. array with the same dimension the compiler would add
  1198. 10*sizeof(int) which, on my machine, would be 20.  Thus, the
  1199. address of the "9" in the 4th row above would be &multi[3][0] or
  1200. *(multi + 3) in pointer notation.  To get to the content of the
  1201. 2nd element in the 4th row we add 1 to this address and
  1202. dereference the result as in
  1203.  
  1204.     *(*(multi + 3) + 1)
  1205.  
  1206.     With a little thought we can see that:
  1207.  
  1208.     *(*(multi + row) + col)    and
  1209.     multi[row][col]            yield the same results.
  1210.  
  1211.     The following program illustrates this using integer arrays
  1212. instead of character arrays.
  1213.  
  1214. ------------------- program 6.1 ----------------------
  1215. /* Program 6.1 from PTRTUT02.TXT   12/14/95 */
  1216.   
  1217. #include <stdio.h>
  1218.  
  1219. #define ROWS 5
  1220. #define COLS 10
  1221.  
  1222. int multi[ROWS][COLS];
  1223.  
  1224. int main(void)
  1225. {
  1226.   int row, col;
  1227.   for (row = 0; row < ROWS; row++)
  1228.     for(col = 0; col < COLS; col++)
  1229.       multi[row][col] = row*col;
  1230.   for (row = 0; row < ROWS; row++)
  1231.     for(col = 0; col < COLS; col++)
  1232.     {
  1233.       printf("\n%d  ",multi[row][col]);
  1234.       printf("%d ",*(*(multi + row) + col));
  1235.     }
  1236.   return 0;
  1237. }
  1238. ----------------- end of program 6.1 ---------------------
  1239.  
  1240.     Because of the double de-referencing required in the pointer
  1241. version, the name of a 2 dimensional array is often said to be
  1242. equivalent to a pointer to a pointer.  With a three dimensional
  1243. array we would be dealing with an array of arrays of arrays and
  1244. some might say its name would be equivalent to a pointer to a
  1245. pointer to a pointer.  However, here we have initially set aside
  1246. the block of memory for the array by defining it using array
  1247. notation.  Hence, we are dealing with a constant, not a variable.
  1248. That is we are talking about a fixed address not a variable
  1249. pointer.  The dereferencing function used above permits us to
  1250. access any element in the array of arrays without the need of
  1251. changing the value of that address (the address of multi[0][0] as
  1252. given by the symbol "multi").
  1253.  
  1254. ->================================================================
  1255. CHAPTER 7: More on Multi-Dimensional Arrays
  1256.  
  1257.     In the previous chapter we noted that given
  1258.  
  1259.   #define ROWS 5
  1260.   #define COLS 10
  1261.  
  1262.   int multi[ROWS][COLS];
  1263.  
  1264. we can access individual elements of the array "multi" using
  1265. either:
  1266.  
  1267.     multi[row][col]    or  *(*(multi + row) + col)
  1268.  
  1269. To understand more fully what is going on, let us replace
  1270.  
  1271.     *(multi + row)    with   X   as in:
  1272.  
  1273.     *(X + col)
  1274.  
  1275.     Now, from this we see that X is like a pointer since the
  1276. expression is de-referenced and we know that col is an integer.
  1277. Here the arithmetic being used is of a special kind called
  1278. "pointer arithmetic" is being used.  That means that, since we
  1279. are talking about an integer array, the address pointed to by
  1280. (i.e. value of)   X + col + 1   must be greater than the address
  1281. X + col   by and amount equal to sizeof(int).
  1282.  
  1283.     Since we know the memory layout for 2 dimensional arrays, we
  1284. can determine that in the expression     multi + row    as used
  1285. above,   multi + row + 1    must increase by value an amount
  1286. equal to that needed to "point to" the next row, which in this
  1287. case would be an amount equal to     COLS * sizeof(int).
  1288.  
  1289.     That says that if the expression     *(*(multi + row) + col)
  1290. is to be evaluated correctly at run time, the compiler must
  1291. generate code which takes into consideration the value of COLS,
  1292. i.e. the 2nd dimension.  Because of the equivalence of the two
  1293. forms of expression, this is true whether we are using the
  1294. pointer expression as here or the array expression
  1295. multi[row][col].
  1296.  
  1297. Thus, to evaluate either expression, a total of 5 values must be
  1298. known:
  1299.  
  1300.     1)  The address of the first element of the array, which is
  1301.         returned by the expression  "multi", i.e. the name of the
  1302.         array.
  1303.  
  1304.     2)  The size of the type of the elements of the array,  in
  1305.         this case sizeof(int).
  1306.  
  1307.     3)  The 2nd dimension of the array
  1308.  
  1309.     4)  The specific index value for the first dimension, "row"
  1310.         in this case.
  1311.  
  1312.     5)  The specific index value for the second dimension, "col"
  1313.         in this case.
  1314.  
  1315.     Given all of that, consider the problem of designing a
  1316. function to manipulate the element values of a previously
  1317. declared array. For example, one which would set all the elements
  1318. of the array "multi" to the value 1.
  1319.  
  1320.    void set_value(int m_array[][COLS])
  1321.    {
  1322.      int row, col;
  1323.      for(row = 0; row < ROWS; row++)
  1324.      {
  1325.        for(col = 0; col < COLS; col++)
  1326.        {
  1327.           m_array[row][col] = 1;
  1328.        }
  1329.      }
  1330.    }
  1331.  
  1332. And to call this function we would then use:
  1333.  
  1334.     set_value(multi);
  1335.  
  1336.     Now, within the function we have used the values #defined by
  1337. ROWS and COLS which set the limits on the for loops. But, these
  1338. #defines are just constants as far as the compiler is concerned,
  1339. i.e. there is nothing to connect them to the array size within
  1340. the function.  row and col are local variables, of course.  The
  1341. formal parameter definition informs the compiler that we are
  1342. talking about an integer array.  We really don't need the first
  1343. dimension and, as will be seen later, there are occasions where
  1344. we would prefer not to define it within the parameter definition
  1345. so, out of habit or consistency, I have not used it here.  But,
  1346. the second dimension _must_ be used as has been shown in the
  1347. expression for the parameter.  The reason is that it is needed in
  1348. the evaluation of   m_array[row][col]   as has been described.
  1349. The reason is that while the parameter defines the data type (int
  1350. in this case) and the automatic variables for row and column are
  1351. defined in the for loops, only one value can be passed using a
  1352. single parameter.  In this case, that is the value of "multi" as
  1353. noted in the call statement, i.e. the address of the first
  1354. element, often referred to as a pointer to the array. Thus, the
  1355. only way we have of informing the compiler of the 2nd dimension
  1356. is by explicitly including it in the parameter definition.
  1357.  
  1358.     In fact, in general all dimensions of higher order than one
  1359. are needed when dealing with multi-dimensional arrays.  That is
  1360. if we are talking about 3 dimensional arrays, the 2nd _and_ 3rd
  1361. dimension must be specified in the parameter definition.
  1362.  
  1363. ->================================================================
  1364. CHAPTER 8: Pointers to Arrays
  1365.  
  1366.     Pointers, of course, can be "pointed at" any type of data
  1367. object, including arrays.  While that was evident when we
  1368. discussed program 3.1, it is important to expand on how we do
  1369. this when it comes to multi-dimensional arrays.
  1370.  
  1371.     To review, in Chapter 2 we stated that given an array of
  1372. integers we could point an integer pointer at that array using:
  1373.  
  1374.     int *ptr;
  1375.  
  1376.     ptr = &my_array[0];       /* point our pointer at the first
  1377.                                  integer in our array */
  1378.  
  1379. As we stated there, the type of the pointer variable must match
  1380. the type of the first element of the array.
  1381.  
  1382.     In addition, we can use a pointer as a formal parameter of a
  1383. function which is designed to manipulate an array.  e.g.
  1384.  
  1385.     Given:
  1386.  
  1387.       int array[3] = {'1', '5', '7'};
  1388.  
  1389.       void a_func(int *p);
  1390.  
  1391. we can pass the address of the array to the function by making
  1392. the call
  1393.  
  1394.         a_func(array);
  1395.  
  1396. This kind of code promotes the mis-conception that pointers and
  1397. arrays are the same thing.  Of course, if you have followed this
  1398. text carefully up to this point you know the difference between a
  1399. pointer and an array.  The function would be better written (in
  1400. terms of clarity) as       a_func(int p[]);     Note that here
  1401. we need not include the dimension since what we are passing is
  1402. the address of the array, not the array itself.
  1403.  
  1404.     We now turn to the problem of the 2 dimensional array.  As
  1405. stated in the last chapter, C interprets a 2 dimensional array as
  1406. an array of one dimensional arrays.  That being the case, the
  1407. first element of a 2 dimensional array of integers is a one
  1408. dimensional array of integers.  And a pointer to a two
  1409. dimensional array of integers must be a pointer to that data
  1410. type.  One way of accomplishing this is through the use of the
  1411. keyword "typedef".  typedef assigns a new name to a specified
  1412. data type.  For example:
  1413.  
  1414.    typedef unsigned char byte;
  1415.  
  1416. provides the name "byte" to mean type "unsigned char".  Hence
  1417.  
  1418.   byte b[10];     would be an array of unsigned characters.
  1419.  
  1420. Note that in the typedef declaration, the word "byte" has
  1421. replaced that which would normally be the name of our unsigned
  1422. char.  That is, the rule for using typedef is that the new name
  1423. for the data type is the name used in the definition of the data
  1424. type.  Thus in:
  1425.  
  1426.     typedef int Array[10];
  1427.  
  1428. Array becomes a data type for an array of 10 integers.  i.e.
  1429.  
  1430.     Array my_arr;
  1431.  
  1432. declares my_arr as an array of 10 integers and
  1433.  
  1434.     Array arr2d[5];
  1435.  
  1436. makes arr2d an array of 5 arrays of 10 integers each.
  1437.  
  1438.     Also note that      Array *p1d;    makes p1d a pointer to an
  1439. array of 10 integers.  Because *p1d points to the same type as
  1440. arr2d, assigning the address of the two dimensional array arr2d to
  1441. p1d, the pointer to a one dimensional array of 10 integers is
  1442. acceptable.  i.e.       p1d = &arr2d[0];     or   p1d = arr2d;
  1443. are both correct.
  1444.  
  1445.     Since the data type we use for our pointer is an array of 10
  1446. integers we would expect that incrementing p1d by 1 would change
  1447. its value by 10*sizeof(int), which it does.  That is sizeof(*p1d)
  1448. is 20.  You can prove this to yourself by writing and running a
  1449. simple short program.
  1450.  
  1451.     Now, while using typedef makes things clearer for the reader
  1452. and easier on the programmer, it is not really necessary.  What
  1453. we need is a way of declaring a pointer like p1d without the need
  1454. of the typedef keyword.  It turns out that this can be done and
  1455. that   int (*p1d)[10];  is the proper declaration, i.e. p1d here
  1456. is a pointer to an array of 10 integers just as it was under the
  1457. declaration using the Array type.  Note that this is different
  1458. than    int *p1d[10];     which would make p1d the name of an
  1459. array of 10 pointers to type int.
  1460.  
  1461. ->================================================================
  1462. CHAPTER 9: Pointers and Dynamic Allocation of Memory
  1463.  
  1464.     There are times when it is convenient to allocate memory at
  1465. run time using malloc(), calloc(), or other allocation functions.
  1466. Using this approach permits postponing the decision on the size
  1467. of the memory block need to store an array, for example, until
  1468. run time.  Or it permits using a section of memory for the
  1469. storage of an array of integers at one point in time, and then
  1470. when that memory is no longer needed it can be freed up for other
  1471. uses, such as the storage of an array of structures.
  1472.  
  1473.     When memory is allocated, the allocating function (such as
  1474. malloc(), calloc(), etc.) returns a pointer.  The type of this
  1475. pointer depends on whether you are using an older K&R compiler or
  1476. the newer ANSI type compiler.  With the older compiler the type
  1477. of the returned pointer is char, with the ANSI compiler it is
  1478. void.
  1479.  
  1480.     If you are using an older compiler, and you want to allocate
  1481. memory for an array  of integers you will have to cast the char
  1482. pointer returned to an integer pointer.  For example, to allocate
  1483. space for 10 integers we might write:
  1484.  
  1485.     int *iptr;
  1486.     iptr = (int *)malloc(10 * sizeof(int));
  1487.     if(iptr == NULL)
  1488.     { .. ERROR ROUTINE GOES HERE .. }
  1489.  
  1490.     If you are using an ANSI compliant compiler, malloc() returns
  1491. a void pointer and since a void pointer can be assigned to a
  1492. pointer variable of any object type, the (int *) cast shown above
  1493. is not needed.  The array dimension can be determined at run time
  1494. and is not needed at compile time.  That is, the "10" above could
  1495. be a variable read in from a data file or keyboard, or calculated
  1496. based on some need, at run time.
  1497.  
  1498.     Because of the equivalence between array and pointer
  1499. notation, once iptr has been assigned as above, one can use the
  1500. array notation.  For example, one could write:
  1501.  
  1502.     int k;
  1503.     for(k = 0; k < 10; k++)
  1504.        iptr[k] = 2;
  1505.  
  1506. to set the values of all elements to 2.
  1507.  
  1508.     Even with a reasonably good understanding of pointers and
  1509. arrays, one place the newcomer to C is likely to stumble at first
  1510. is in the dynamic allocation of multi-dimensional arrays.  In
  1511. general, we would like to be able to access elements of such
  1512. arrays using array notation, not pointer notation, wherever
  1513. possible. Depending on the application we may or may not know
  1514. both dimensions at compile time.  This leads to a variety of ways
  1515. to go about our task.
  1516.  
  1517.     As we have seen, when dynamically allocating a one
  1518. dimensional array the dimension can be determined at run time.
  1519. Now, when using dynamic allocation of higher order arrays, we
  1520. never need to know the first dimension at compile time.  Whether
  1521. we need to know the higher dimensions depends on how we go about
  1522. writing the code.  Here I will discuss various methods of
  1523. dynamically allocating room for 2 dimensional arrays of integers.
  1524.  
  1525.     First we will consider cases where the 2nd dimension is known
  1526. at compile time.
  1527.  
  1528. METHOD 1:
  1529.  
  1530.     One way of dealing with the problem is through the use of the
  1531. "typedef" keyword.  To allocate a 2 dimensional array of integers
  1532. recall that the following two notations result in the same object
  1533. code being generated:
  1534.  
  1535. multi[row][col] = 1;     *(*(multi + row) + col) = 1;
  1536.  
  1537.     It is also true that the following two notations generate the
  1538. same code:
  1539.  
  1540.     multi[row]            *(multi + row)
  1541.  
  1542.     Since the one on the right must evaluate to a pointer, the
  1543. array notation on the left must also evaluate to a pointer.  In
  1544. fact multi[0] will return a pointer to the first integer in the
  1545. first row, multi[1] a pointer to the first integer of the second
  1546. row, etc.  Actually, multi[n] evaluates to a pointer to that
  1547. array of integers which makes up the n-th row of our 2
  1548. dimensional array. That is, multi can be thought of as an array
  1549. of arrays and multi[n] as a pointer to the n-th array of this
  1550. array of arrays.  Here the word "pointer" is being used
  1551. to represent an address value.  While such usage is common in the
  1552. literature, when reading such statements one must be careful to
  1553. distinguish between the constant address of an array and a
  1554. variable pointer which is a data object in itself.
  1555.  
  1556. Consider now:
  1557. --------------- Program 9.1 --------------------------------
  1558. /* Program 9.1 from PTRTUT02.TXT   12/14/95 */
  1559.  
  1560. #include <stdio.h>
  1561. #include <alloc.h>
  1562.  
  1563. #define COLS 5
  1564.  
  1565. typedef int RowArray[COLS];
  1566. RowArray *rptr;
  1567.  
  1568. int main(void)
  1569. {
  1570.   int nrows = 10;
  1571.   int row, col;
  1572.   rptr = malloc(nrows * COLS * sizeof(int));
  1573.   for(row = 0; row < nrows; row++)
  1574.    for(col = 0; col < COLS; col++)
  1575.    {
  1576.      rptr[row][col] = 17;
  1577.    }
  1578.    return 0;
  1579. }
  1580. ------------- End of Prog. 9.1 --------------------------------
  1581.     Here I have assumed an ANSI compiler so a cast on the void
  1582. pointer returned by malloc() is not required.  If you are using
  1583. an older K&R compiler you will have to cast using:
  1584.  
  1585.     rptr = (RowArray *)malloc(.... etc.
  1586.  
  1587.     Using this approach, "rptr" has all the characteristics of an
  1588. array name and array notation may be used throughout the rest of
  1589. the program.  That also means that if you intend to write a
  1590. function to modify the array contents, you must use COLS as a
  1591. part of the formal parameter in that function, just as we did
  1592. when discussing the passing of two dimensional arrays to a
  1593. function.
  1594.  
  1595. METHOD 2:
  1596.  
  1597.     In the METHOD 1 above, rptr turned out to be a pointer to
  1598. type "one dimensional array of COLS integers".  It turns out that
  1599. there is syntax which can be used for this type without the need
  1600. of typedef.  If we write:
  1601.  
  1602. int (char *xptr)[COLS];
  1603.  
  1604. the variable xptr will have all the same characteristics as the
  1605. variable rptr in METHOD 1 above, and we need not use the
  1606. "typedef" keyword.  Here xptr is a pointer to an array of
  1607. integers and the size of that array is given by the #defined
  1608. COLS.  The parenthesis placement makes the pointer notation
  1609. predominate, even though the array notation has higher
  1610. precedence.  i.e. had we written
  1611.  
  1612. int char *xptr[COLS];
  1613.  
  1614. we would have defined xptr as an array of pointers holding the
  1615. number of pointers equal to that #defined by COLS.  Which is not
  1616. the same thing at all.  However, arrays of pointers have their
  1617. use in the dynamic allocation of two dimensional arrays, as will
  1618. be seen in the next 2 methods.
  1619.  
  1620. METHOD 3:
  1621.  
  1622.    Consider the case where we do not know the number of elements
  1623. in each row at compile time, i.e. both the number of rows and
  1624. number of columns must be determined at run time.  One way of
  1625. doing this would be to create an array of pointers to type int
  1626. and then allocate space for each row and point these pointers at
  1627. each row.  Consider:
  1628. -------------- Program 9.2 ------------------------------------
  1629. /* Program 9.2 from PTRTUT02.TXT   12/14/95 */
  1630.  
  1631. #include <stdio.h>
  1632. #include <stdlib.h>
  1633.  
  1634. int main(void)
  1635. {
  1636.   int nrows = 5;     /* Both nrows and ncols could be evaluated */
  1637.   int ncols = 10;    /* or read in at run time */
  1638.   int row;
  1639.   int **rowptr;
  1640.   rowptr = malloc(nrows * sizeof(int *));
  1641.   if(rowptr == NULL)
  1642.   {
  1643.     puts("\nFailure to allocate room for row pointers.\n");
  1644.     exit(0);
  1645.   }
  1646.   printf("\n\n\nIndex   Pointer(hex)   Pointer(dec)   Diff.(dec)");
  1647.  
  1648.   for(row = 0; row < nrows; row++)
  1649.   {
  1650.     rowptr[row] = malloc(ncols * sizeof(int));
  1651.     if(rowptr[row] == NULL)
  1652.     {
  1653.       printf("\nFailure to allocate for row[%d]\n",row);
  1654.       exit(0);
  1655.     }
  1656.     printf("\n%d         %p         %d", row, rowptr[row], rowptr[row]);
  1657.     if(row > 0)
  1658.       printf("              %d",(int)(rowptr[row] - rowptr[row-1]));
  1659.   }
  1660.   return 0;
  1661. }
  1662. --------------- End 9.2 ------------------------------------
  1663.  
  1664.     In the above code rowptr is a pointer to pointer to type int.
  1665. In this case it points to the first element of an array of
  1666. pointers to type int.  Consider the number of calls to malloc():
  1667.  
  1668.   To get the array of pointers             1     call
  1669.   To get space for the rows                5     calls
  1670.                                         -----
  1671.                    Total                   6     calls
  1672.  
  1673.     If you choose to use this approach note that while you can
  1674. use the array notation to access individual elements of the
  1675. array, e.g.  rowptr[row][col] = 17;, it does not mean that the
  1676. data in the "two dimensional array" is contiguous in memory.
  1677.  
  1678.     But, you can use the array notation just as if it were a
  1679. continuous block of memory.  For example, you can write:
  1680.  
  1681.   rowptr[row][col] = 176;
  1682.  
  1683. just as if rowptr were the name of a two dimensional array
  1684. created at compile time.  Of course 'row' and 'col' must be
  1685. within the bounds of the array you have created, just as with an
  1686. array created at compile time.
  1687.  
  1688.     If it is desired to have a contiguous block of memory
  1689. dedicated to the storage of the elements in the array it can be
  1690. done as follows:
  1691.  
  1692. METHOD 4:
  1693.  
  1694.     In this method we allocate a block of memory to hold the
  1695. whole array first.  We then create an array of pointers to point
  1696. to each row.  Thus even though the array of pointers is being
  1697. used, the actual array in memory is contiguous.  The code looks
  1698. like this:
  1699.  
  1700. ----------------- Program 9.3 -----------------------------------
  1701. /* Program 9.3 from PTRTUT02.TXT   12/14/95 */
  1702.  
  1703. #include <stdio.h>
  1704. #include <stdlib.h>
  1705. #include <conio.h>
  1706.  
  1707. int main(void)
  1708. {
  1709.   int **rptr;
  1710.   int *aptr;
  1711.   int *testptr;
  1712.   int k;
  1713.   int nrows = 5;     /* Both nrows and ncols could be evaluated */
  1714.   int ncols = 10;    /* or read in at run time */
  1715.   int row, col;
  1716.      /* we now allocate the memory for the array */
  1717.   aptr = malloc(nrows * ncols * sizeof(int));
  1718.   if(aptr == NULL)
  1719.   {
  1720.     puts("\nFailure to allocate room for the array");
  1721.     exit(0);
  1722.   }
  1723.      /* next we allocate room for the pointers to the rows */
  1724.   rptr = malloc(nrows * sizeof(int *));
  1725.   if(rptr == NULL)
  1726.   {
  1727.     puts("\nFailure to allocate room for pointers");
  1728.     exit(0);
  1729.   }
  1730.      /* and now we 'point' the pointers */
  1731.   clrscr();
  1732.   for(k = 0; k < nrows; k++)
  1733.   {
  1734.      rptr[k] = aptr + (k * ncols);
  1735.   }
  1736.   printf("\n\n\nIndex   Pointer(hex)   Pointer(dec)   Diff.(dec)");
  1737.  
  1738.   for(row = 0; row < nrows; row++)
  1739.   {
  1740.     printf("\n%d         %p         %d", row, rptr[row], rptr[row]);
  1741.     if(row > 0)
  1742.       printf("              %d",(int)(rptr[row] - rptr[row-1]));
  1743.   }
  1744.   for(row = 0; row < nrows; row++)
  1745.   {
  1746.      for(col = 0; col < ncols; col++)
  1747.      {
  1748.        rptr[row][col] = row + col;
  1749.        printf("%d ", rptr[row][col]);
  1750.      }
  1751.      putchar('\n');
  1752.   }
  1753.   puts("\n\n\n");
  1754.  
  1755.      /* and here we illustrate that we are, in fact, dealing with
  1756.         a 2 dimensional array in a _contiguous_ block of memory. */
  1757.  
  1758.   testptr = aptr;
  1759.   for(row = 0; row < nrows; row++)
  1760.   {
  1761.     for(col = 0; col < ncols; col++)
  1762.     {
  1763.       printf("%d ", *(testptr++));
  1764.     }
  1765.     putchar('\n');
  1766.   }
  1767.   return 0;
  1768. }
  1769.  
  1770. ------------- End Program 9.3 -----------------
  1771.  
  1772. Consider again, the number of calls to malloc()
  1773.  
  1774.     To get room for the array itself      1      call
  1775.     To get room for the array of ptrs     1      call
  1776.                                         ----
  1777.                          Total            2      calls
  1778.  
  1779.     Now, each call to malloc() creates additional space overhead
  1780. since malloc() is generally implemented by the operating system
  1781. forming a linked list which contains data concerning the size of
  1782. the block.  But, more importantly, with large arrays (several
  1783. hundred rows) keeping track of what needs to be freed when the
  1784. time comes can be more cumbersome.  This, combined with he
  1785. contiguousness of the data block which permits initialization to
  1786. all zeroes using memset() would seem to make the second
  1787. alternative the preferred one.
  1788.  
  1789.  
  1790.     As a final example on multidimensional arrays we will
  1791. illustrate the dynamic allocation of a three dimensional array.
  1792. This example will illustrate one more thing to watch when doing
  1793. this kind of allocation.  For reasons cited above we will use the
  1794. approach outlined in alternative two.  Consider the following
  1795. code:
  1796.  
  1797. ------------------- Program 9.4 -------------------------------------
  1798. /* Program 9.4 from PTRTUT02.TXT   12/14/95 */
  1799.  
  1800. #include <stdio.h>
  1801. #include <stdlib.h>
  1802. #include <mem.h>
  1803. #include <conio.h>
  1804.  
  1805. int X_DIM=16;
  1806. int Y_DIM=8;
  1807. int Z_DIM=4;
  1808.  
  1809. int main(void)
  1810. {
  1811.   char ***space;
  1812.   char ***Arr3D;
  1813.   int y, z;
  1814.   ptrdiff_t diff;
  1815.  
  1816.   /* first we set aside space for the array itself */
  1817.  
  1818.   space = malloc(X_DIM * Y_DIM * Z_DIM * sizeof(char));
  1819.  
  1820.   /* next we allocate space of an array of pointers, each
  1821.      to eventually point to the first element of a
  1822.      2 dimensional array of pointers to pointers */
  1823.  
  1824.   Arr3D = malloc(Z_DIM * sizeof(char **));
  1825.  
  1826.   /* and for each of these we assign a pointer to a newly
  1827.      allocated array of pointers to a row */
  1828.  
  1829.   for(z = 0; z < Z_DIM; z++)
  1830.   {
  1831.      Arr3D[z] = malloc(Y_DIM * sizeof(char *));
  1832.  
  1833.      /* and for each space in this array we put a pointer to
  1834.         the first element of each row in the array space
  1835.         originally allocated */
  1836.  
  1837.      for(y = 0; y < Y_DIM; y++)
  1838.      {
  1839.        Arr3D[z][y] = ((char *)space + (z*(X_DIM * Y_DIM) + y*X_DIM));
  1840.      }
  1841.   }
  1842.  
  1843.   /* And, now we check each address in our 3D array to see if
  1844.      the indexing of the Arr3d pointer leads through in a
  1845.      continuous manner */
  1846.  
  1847.   for(z = 0; z < Z_DIM; z++)
  1848.   {
  1849.     printf("Location of array %d is %p\n", z, *Arr3D[z]);
  1850.     for( y = 0; y < Y_DIM; y++)
  1851.     {
  1852.        printf("  Array %d and Row %d starts at %p", z, y, Arr3D[z][y]);
  1853.        diff = Arr3D[z][y] - (char *)space;
  1854.        printf("    diff = %d  ",diff);
  1855.        printf(" z = %d  y = %d\n", z, y);
  1856.     }
  1857.     getch();
  1858.   }
  1859.   return 0;
  1860. }
  1861.  
  1862.  
  1863. ------------------- End of Prog. 9.4 ----------------------------
  1864.     If you have followed this tutorial up to this point you
  1865. should have no problem deciphering the above on the basis of the
  1866. comments alone.  There is one line that deserves a bit of special
  1867. attention however.  It reads:
  1868.  
  1869.   Arr3D[z][y] = ((char *)space + (z*(X_DIM * Y_DIM) + y*X_DIM));
  1870.  
  1871.     Note that here "space" is cast to a character pointer, which
  1872. is the same type as Arr3D[z][y].  A thing to be careful of,
  1873. however, is where that cast is made.  If the cast were made
  1874. outside the overall parenthesis as in...
  1875.  
  1876.   Arr3D[z][y] = (char *)(space + (z*(X_DIM * Y_DIM) + y*X_DIM));
  1877.  
  1878. the code fails.  The reason is that the cast, in this case, is
  1879. not so much to make the types on each side of the assignment
  1880. operator match, as it is to make the pointer arithmetic work.
  1881. Recall that when dealing with pointer arithmetic in something
  1882. like:
  1883.  
  1884. int *ptr;
  1885. ptr = ptr + 1;
  1886.  
  1887. the second line increments the pointer by sizeof(int), which is 2
  1888. on MS-DOS machines.  Now looking at the mentioned line, it should
  1889. be obvious that
  1890.  
  1891.          (z*(X_DIM * Y_DIM) + y*X_DIM))
  1892.  
  1893. calculates the number of array elements This will turn out to be
  1894. an arithmetic constant after the calculation.  Now since we are
  1895. dealing with an array of characters the result of the pointer
  1896. arithmetic which adds this value to the pointer to the start of
  1897. the array should yield a value equal to the pointer value plus
  1898. this constant.  Were we using an int data type, i.e. casting our
  1899. "space" pointer to (int *), the actual value by which the pointer
  1900. would be incremented would be the calculated value times
  1901. sizeof(int).
  1902.  
  1903. ->==================================================================
  1904. CHAPTER 10: Pointers to Functions
  1905.  
  1906.     Up to this point we have been discussing pointers to data
  1907. objects.  C also permits the declaration of pointers to
  1908. functions.  Pointers to functions have a variety of uses and some
  1909. of them will be discussed here.
  1910.  
  1911.     Consider the following real problem.  You want to write a
  1912. function that is capable of sorting virtually any collection of
  1913. data that can be stored in an array.  This might be an array of
  1914. strings, or integers, or floats, or even structures.  The sorting
  1915. algorithm can be the same for all.  For example, it could be a
  1916. simple bubble sort algorithm, or the more complex shell or quick
  1917. sort algorithm.  We'll use a simple bubble sort for demonstration
  1918. purposes.
  1919.  
  1920.     Sedgewick [1] has described the bubble sort using C code by
  1921. setting up a function which when passed a pointer to the array
  1922. would sort it.  If we call that function bubble(), a sort program
  1923. is described by bubble_1.c, which follows:
  1924.  
  1925. /*-------------------- bubble_1.c --------------------*/
  1926. /* Program bubble_1.c from PTRTUT02.TXT   12/14/95 */
  1927.  
  1928. #include <stdio.h>
  1929.  
  1930. int arr[10] = { 3,6,1,2,3,8,4,1,7,2};
  1931.  
  1932. void bubble(int a[], int N);
  1933.  
  1934. int main(void)
  1935. {
  1936.   int i;
  1937.   putchar('\n');
  1938.   for(i = 0; i < 10; i++)
  1939.   {
  1940.     printf("%d ", arr[i]);
  1941.   }
  1942.   bubble(arr,10);
  1943.   putchar('\n');
  1944.   for(i = 0; i < 10; i++)
  1945.   {
  1946.     printf("%d ", arr[i]);
  1947.   }
  1948.   return 0;
  1949. }
  1950.  
  1951. void bubble(int a[], int N)
  1952. {
  1953.  int i, j, t;
  1954.  for(i = N-1; i >= 0; i--)
  1955.    for(j = 1; j <= i; j++)
  1956.      if(a[j-1] > a[j])
  1957.        {
  1958.          t = a[j-1];
  1959.          a[j-1] = a[j];
  1960.          a[j] = t;
  1961.        }
  1962. }
  1963. /*---------------------- end bubble_1.c -----------------------*/
  1964.  
  1965. The bubble sort is one of the simpler sorts.  The algorithm scans
  1966. the array from the second to the last element comparing each
  1967. element with the one which precedes it. If the one that precedes
  1968. it is larger than the current element, the two are swapped so the
  1969. larger one is closer to the end of the array.  On the first pass,
  1970. this results in the largest element ending up at the end of the
  1971. array.  The array is now limited to all elements except the last
  1972. and the process repeated.  This puts the next largest element at
  1973. a point preceding the largest element.  The process is repeated
  1974. for a number of times equal to the number of elements minus 1.
  1975. The end result is a sorted array.
  1976.  
  1977.      Here our function is designed to sort an array of integers.
  1978. Thus in line 1 we are comparing integers and in lines 2 through 4
  1979. we are using temporary integer storage to store integers.  What
  1980. we want to do now is see if we can convert this code so we can
  1981. use any data type, i.e. not be restricted to integers.
  1982.  
  1983.     At the same time we don't want to have to analyze our
  1984. algorithm and the code associated with it each time we use it.
  1985. We start by removing the comparison from within the function
  1986. bubble() so as to make it relatively easy to modify the
  1987. comparison function without having to re-write portions related
  1988. to the actual algorithm.  This results in bubble_2.c:
  1989.  
  1990. /*---------------------- bubble_2.c -------------------------*/
  1991. /* Program bubble_2.c from PTRTUT02.TXT   12/14/95 */
  1992.  
  1993.    /* Separating the comparison function */
  1994.  
  1995. #include <stdio.h>
  1996.  
  1997. int arr[10] = { 3,6,1,2,3,8,4,1,7,2};
  1998.  
  1999. void bubble(int a[], int N);
  2000. int compare(int m, int n);
  2001.  
  2002. int main(void)
  2003. {
  2004.   int i;
  2005.   putchar('\n');
  2006.   for(i = 0; i < 10; i++)
  2007.   {
  2008.     printf("%d ", arr[i]);
  2009.   }
  2010.   bubble(arr,10);
  2011.   putchar('\n');
  2012.   for(i = 0; i < 10; i++)
  2013.   {
  2014.     printf("%d ", arr[i]);
  2015.   }
  2016.   return 0;
  2017. }
  2018.  
  2019. void bubble(int a[], int N)
  2020. {
  2021.  int i, j, t;
  2022.  for(i = N-1; i >= 0; i--)
  2023.    for(j = 1; j <= i; j++)
  2024.      if (compare(a[j-1], a[j]))
  2025.        {
  2026.          t = a[j-1];
  2027.          a[j-1] = a[j];
  2028.          a[j] = t;
  2029.        }
  2030. }
  2031.  
  2032. int compare(int m, int n)
  2033. {
  2034.   return (m > n);
  2035. }
  2036. /*--------------------- end of bubble_2.c -----------------------*/
  2037.  
  2038. If our goal is to make our sort routine data type independent,
  2039. one way of doing this is to use pointers to type void to point to
  2040. the data instead of using the integer data type.  As a start in
  2041. that direction let's modify a few things in the above so that
  2042. pointers can be used.  To begin with, we'll stick with pointers
  2043. to type integer.
  2044.  
  2045. /*----------------------- bubble_3.c -------------------------*/
  2046. /* Program bubble_3.c from PTRTUT02.TXT   12/14/95 */
  2047.  
  2048. #include <stdio.h>
  2049.  
  2050. int arr[10] = { 3,6,1,2,3,8,4,1,7,2};
  2051.  
  2052. void bubble(int *p, int N);
  2053. int compare(int *m, int *n);
  2054.  
  2055. int main(void)
  2056. {
  2057.   int i;
  2058.   putchar('\n');
  2059.   for(i = 0; i < 10; i++)
  2060.   {
  2061.     printf("%d ", arr[i]);
  2062.   }
  2063.   bubble(arr,10);
  2064.   putchar('\n');
  2065.   for(i = 0; i < 10; i++)
  2066.   {
  2067.     printf("%d ", arr[i]);
  2068.   }
  2069.   return 0;
  2070. }
  2071.  
  2072. void bubble(int *p, int N)
  2073. {
  2074.  int i, j, t;
  2075.  for(i = N-1; i >= 0; i--)
  2076.    for(j = 1; j <= i; j++)
  2077.      if (compare(&p[j-1], &p[j]))
  2078.        {
  2079.          t = p[j-1];
  2080.          p[j-1] = p[j];
  2081.          p[j] = t;
  2082.        }
  2083. }
  2084.  
  2085. int compare(int *m, int *n)
  2086. {
  2087.   return (*m > *n);
  2088. }
  2089. /*------------------ end of bubble3.c -------------------------*/
  2090.  
  2091. Note the changes. We are now passing a pointer to an integer (or
  2092. array of integers) to bubble().  And from within bubble we are
  2093. passing pointers to the elements of the array that we want to
  2094. compare to our comparison function.  And, of course we are
  2095. dereferencing these pointer in our compare() function in order to
  2096. make the actual comparison.  Our next step will be to convert the
  2097. pointers in bubble() to pointers to type void so that that
  2098. function will become more type insensitive.  This is shown in
  2099. bubble_4.
  2100.  
  2101. /*------------------ bubble_4.c ----------------------------*/
  2102. /* Program bubble_4.c from PTRTUT02.TXT   12/14/95 */
  2103.  
  2104. #include <stdio.h>
  2105.  
  2106. int arr[10] = { 3,6,1,2,3,8,4,1,7,2};
  2107.  
  2108. void bubble(int *p, int N);
  2109. int compare(void *m, void *n);
  2110.  
  2111. int main(void)
  2112. {
  2113.   int i;
  2114.   putchar('\n');
  2115.   for(i = 0; i < 10; i++)
  2116.   {
  2117.     printf("%d ", arr[i]);
  2118.   }
  2119.   bubble(arr,10);
  2120.   putchar('\n');
  2121.   for(i = 0; i < 10; i++)
  2122.   {
  2123.     printf("%d ", arr[i]);
  2124.   }
  2125.   return 0;
  2126. }
  2127.  
  2128. void bubble(int *p, int N)
  2129. {
  2130.  int i, j, t;
  2131.  for(i = N-1; i >= 0; i--)
  2132.    for(j = 1; j <= i; j++)
  2133.      if (compare((void *)&p[j-1], (void *)&p[j]))
  2134.        {
  2135.          t = p[j-1];
  2136.          p[j-1] = p[j];
  2137.          p[j] = t;
  2138.        }
  2139. }
  2140.  
  2141. int compare(void *m, void *n)
  2142. {
  2143.   int *m1, *n1;
  2144.   m1 = (int *)m;
  2145.   n1 = (int *)n;
  2146.   return (*m1 > *n1);
  2147. }
  2148. /*------------------ end of bubble_4.c ---------------------*/
  2149.  
  2150. Note that, in doing this, in compare() we had to introduce the
  2151. casting of the void pointer types passed to the actual type being
  2152. sorted.  But, as we'll see later that's okay.  And since what is
  2153. being passed to bubble() is still a pointer to an array of
  2154. integers, we had to cast these pointers to void pointers when we
  2155. passed them as parameters in our call to compare().
  2156.  
  2157. We now address the problem of what we pass to bubble().  We want
  2158. to make the first parameter of that function a void pointer also.
  2159. But, that means that within bubble() we need to do something
  2160. about the variable t, which is currently an integer.  Also, where
  2161. we use t = p[j-1];  the type of p[j-1] needs to be known in order
  2162. to know how many bytes to copy to the variable t (or whatever we
  2163. replace t with).
  2164.  
  2165. Currently, in bubble_4.c, knowledge within bubble() as to the
  2166. type of the data being sorted (and hence the size of each
  2167. individual element) is obtained from the fact that the first
  2168. parameter is a pointer to type integer.  If we are going to be
  2169. able to use bubble() to sort any type of data, we need to make
  2170. that pointer a pointer to type void.  But, in doing so we are
  2171. going to lose information concerning the size of individual
  2172. elements within the array.  So, in bubble_5.c we will add a
  2173. separate parameter to handle this size information.
  2174.  
  2175. These changes, from bubble4.c to bubble5.c are, perhaps, a bit
  2176. more extensive than those we have made in the past.  So, compare
  2177. the two modules carefully for differences.
  2178.  
  2179. /*---------------------- bubble5.c ---------------------------*/
  2180. /* Program bubble_5.c from PTRTUT02.TXT   12/14/95 */
  2181.  
  2182. #include <stdio.h>
  2183. #include <string.h>
  2184.  
  2185. long arr[10] = { 3,6,1,2,3,8,4,1,7,2};
  2186.  
  2187. void bubble(void *p, size_t width, int N);
  2188. int compare(void *m, void *n);
  2189.  
  2190. int main(void)
  2191. {
  2192.   int i;
  2193.   putchar('\n');
  2194.   for(i = 0; i < 10; i++)
  2195.   {
  2196.     printf("%d ", arr[i]);
  2197.   }
  2198.   bubble(arr, sizeof(long), 10);
  2199.   putchar('\n');
  2200.   for(i = 0; i < 10; i++)
  2201.   {
  2202.     printf("%d ", arr[i]);
  2203.   }
  2204.   return 0;
  2205. }
  2206.  
  2207. void bubble(void *p, size_t width, int N)
  2208. {
  2209.  int i, j;
  2210.  unsigned char buf[4];
  2211.  unsigned char *bp = p;
  2212.  for(i = N-1; i >= 0; i--)
  2213.    for(j = 1; j <= i; j++)
  2214.      if (compare((void *)(bp + width*(j-1)), (void *)(bp + j*width)))  /* 1 */
  2215.        {
  2216. /*         t = p[j-1];   */
  2217.         memcpy(buf, bp + width*(j-1), width);
  2218. /*         p[j-1] = p[j];   */
  2219.         memcpy(bp + width*(j-1), bp + j*width , width);
  2220. /*         p[j] = t;   */
  2221.         memcpy(bp + j*width, buf, width);
  2222.        }
  2223.  
  2224. }
  2225.  
  2226. int compare(void *m, void *n)
  2227. {
  2228.   long *m1, *n1;
  2229.   m1 = (long *)m;
  2230.   n1 = (long *)n;
  2231.   return (*m1 > *n1);
  2232. }
  2233. /*--------------------- end of bubble5.c ---------------------*/
  2234.  
  2235. Note that I have changed the data type of the array from int to
  2236. long to illustrate the changes needed in the compare() function.
  2237. Within bubble I've done away with the variable t (which we would
  2238. have had to change from type int to type long).  I have added a
  2239. buffer of size 4 unsigned characters, which is the size needed to
  2240. hold a long (this will change again in future modifications to
  2241. this code).  The unsigned character pointer *bp is used to point
  2242. to the base of the array to be sorted, i.e. to the first element
  2243. of that array.
  2244.  
  2245. We also had to modify what we passed to compare(), and how we do
  2246. the swapping of elements that the comparison indicates need
  2247. swapping.  Use of memcpy() and pointer notation instead of array
  2248. notation work towards this reduction in type sensitivity.
  2249.  
  2250. Again, making a careful comparison of bubble5.c with bubble4.c
  2251. can result in improved understanding of what is happening and
  2252. why.
  2253.  
  2254. We move now to bubble6.c where we use the same function bubble()
  2255. that we used in bubble5.c to sort strings instead of long
  2256. integers.  Of course we have to change the comparison function
  2257. since the means by which strings are compared is different from
  2258. that by which long integers are compared.  And,in bubble6.c we
  2259. have deleted the lines within bubble() that were commented out in
  2260. bubble5.c.
  2261.  
  2262. /*--------------------- bubble6.c ---------------------*/
  2263. /* Program bubble_6.c from PTRTUT02.TXT   12/14/95 */
  2264.  
  2265. #include <stdio.h>
  2266. #include <string.h>
  2267.  
  2268. #define MAX_BUF 256
  2269.  
  2270. long arr[10] = { 3,6,1,2,3,8,4,1,7,2};
  2271.  
  2272. char arr2[5][20] = {  "Mickey Mouse",
  2273.                       "Donald Duck",
  2274.                       "Minnie Mouse",
  2275.                       "Goofy",
  2276.                       "Ted Jensen" };
  2277.  
  2278. void bubble(void *p, int width, int N);
  2279. int compare(void *m, void *n);
  2280.  
  2281. int main(void)
  2282. {
  2283.   int i;
  2284.   putchar('\n');
  2285.   for(i = 0; i < 5; i++)
  2286.   {
  2287.     printf("%s\n", arr2[i]);
  2288.   }
  2289.   bubble(arr2, 20, 5);
  2290.   putchar('\n\n');
  2291.   for(i = 0; i < 5; i++)
  2292.   {
  2293.     printf("%s\n", arr2[i]);
  2294.   }
  2295.   return 0;
  2296. }
  2297.  
  2298. void bubble(void *p, int width, int N)
  2299.      {
  2300.       int i, j, k;
  2301.       unsigned char buf[MAX_BUF];
  2302.       unsigned char *bp = p;
  2303.       for(i = N-1; i >= 0; i--)
  2304.         for(j = 1; j <= i; j++)
  2305.         {
  2306.           k = compare((void *)(bp + width*(j-1)), (void *)(bp + j*width));
  2307.           if (k > 0)
  2308.             {
  2309.              memcpy(buf, bp + width*(j-1), width);
  2310.              memcpy(bp + width*(j-1), bp + j*width , width);
  2311.              memcpy(bp + j*width, buf, width);
  2312.             }
  2313.         }
  2314.     }
  2315.  
  2316. int compare(void *m, void *n)
  2317. {
  2318.    char *m1 = m;
  2319.    char *n1 = n;
  2320.    return (strcmp(m1,n1));
  2321. }
  2322. /*------------------- end of bubble6.c ---------------------*/
  2323.  
  2324. But, the fact that bubble() was unchanged from that used in
  2325. bubble5.c indicates that that function is capable of sorting a
  2326. wide variety of data types.  What is left to do is to pass to
  2327. bubble() the name of the comparison function we want to use so
  2328. that it can be truly universal.  Just as the name of an array is
  2329. the address of the first element of the array in the data
  2330. segment, the name of a function decays into the address of that
  2331. function in the code segment.  Thus we need to use a pointer to a
  2332. function.  In this case the comparison function.
  2333.  
  2334. Pointers to functions must match the functions pointed to in the
  2335. number and types of the parameters and the type of the return
  2336. value.  In our case, we declare our function pointer as:
  2337.  
  2338.    int (*fptr)(const void *p1, const void *p2);
  2339.  
  2340. Note that were we to write:
  2341.  
  2342.     int *fptr(const void *p1, const void *p2);
  2343.  
  2344. we would have a function prototype for a function which returned
  2345. a pointer to type int.  That is because in C the parenthesis ()
  2346. operator have a higher precedence than the pointer * operator.
  2347. By putting the parenthesis around the string (*fptr) we indicate
  2348. that we are declaring a function pointer.
  2349.  
  2350. We now modify our declaration of bubble() by adding, as its 4th
  2351. parameter, a function pointer of the proper type.  It's function
  2352. prototype becomes:
  2353.  
  2354.   void bubble(void *p, int width, int N,
  2355.              int(*fptr)(const void *, const void *));
  2356.  
  2357. When we call the bubble(), we insert the name of the comparison
  2358. function that we want to use.  bubble7.c illustrate how this
  2359. approach permits the use of the same bubble() function for
  2360. sorting different types of data.
  2361.  
  2362. /*------------------- bubble7.c ------------------*/
  2363. /* Program bubble_7.c from PTRTUT02.TXT   12/14/95 */
  2364.  
  2365. #include <stdio.h>
  2366. #include <string.h>
  2367.  
  2368. #define MAX_BUF 256
  2369.  
  2370. long arr[10] = { 3,6,1,2,3,8,4,1,7,2};
  2371.  
  2372. char arr2[5][20] = {  "Mickey Mouse",
  2373.                       "Donald Duck",
  2374.                       "Minnie Mouse",
  2375.                       "Goofy",
  2376.                       "Ted Jensen" };
  2377.  
  2378. void bubble(void *p, int width, int N,
  2379.              int(*fptr)(const void *, const void *));
  2380. int compare_string(const void *m, const void *n);
  2381. int compare_long(const void *m, const void *n);
  2382. int main(void)
  2383. {
  2384.   int i;
  2385.   puts("\nBefore Sorting:\n");
  2386.   for(i = 0; i < 10; i++)               /* show the long ints */
  2387.   {
  2388.     printf("%ld ",arr[i]);
  2389.   }
  2390.   puts("\n");
  2391.   for(i = 0; i < 5; i++)                  /* show the strings */
  2392.   {
  2393.     printf("%s\n", arr2[i]);
  2394.   }
  2395.   bubble(arr, 4, 10, compare_long);          /* sort the longs */
  2396.   bubble(arr2, 20, 5, compare_string);     /* sort the strings */
  2397.   puts("\n\nAfter Sorting:\n");
  2398.   for(i = 0; i < 10; i++)             /* show the sorted longs */
  2399.   {
  2400.     printf("%d ",arr[i]);
  2401.   }
  2402.   puts("\n");
  2403.   for(i = 0; i < 5; i++)            /* show the sorted strings */
  2404.   {
  2405.     printf("%s\n", arr2[i]);
  2406.   }
  2407.   return 0;
  2408. }
  2409.  
  2410. void bubble(void *p, int width, int N,
  2411.              int(*fptr)(const void *, const void *))
  2412.      {
  2413.       int i, j, k;
  2414.       unsigned char buf[MAX_BUF];
  2415.       unsigned char *bp = p;
  2416.       for(i = N-1; i >= 0; i--)
  2417.         for(j = 1; j <= i; j++)
  2418.         {
  2419.           k = fptr((void *)(bp + width*(j-1)), (void *)(bp + j*width));
  2420.           if (k > 0)
  2421.             {
  2422.              memcpy(buf, bp + width*(j-1), width);
  2423.              memcpy(bp + width*(j-1), bp + j*width , width);
  2424.              memcpy(bp + j*width, buf, width);
  2425.             }
  2426.         }
  2427.     }
  2428.  
  2429. int compare_string(const void *m, const void *n)
  2430. {
  2431.    char *m1 = (char *)m;
  2432.    char *n1 = (char *)n;
  2433.    return (strcmp(m1,n1));
  2434. }
  2435.  
  2436. int compare_long(const void *m, const void *n)
  2437. {
  2438.   long *m1, *n1;
  2439.   m1 = (long *)m;
  2440.   n1 = (long *)n;
  2441.   return (*m1 > *n1);
  2442. }
  2443. /*----------------- end of bubble7.c -----------------*/
  2444.  
  2445. References for Chapter 10
  2446.  
  2447.   [1]  "Algorithms in C"
  2448.        Robert Sedgewick
  2449.        Addison-Wesley
  2450.        ISBN 0-201-51425-7
  2451.  
  2452. ->==============================================================
  2453. EPILOG
  2454.  
  2455.     I have written the preceding material to provide an
  2456. introduction to pointers for newcomers to C.  In C, the more one
  2457. understands about pointers the greater flexibility one has in the
  2458. writing of code.  The above expands on my first effort at this
  2459. which was entitled ptr_help.txt and found in an early version of
  2460. Bob Stout's collection of C code SNIPPETS.  The content in this
  2461. version is the same as that in PTRTUTOT.ZIP included in
  2462. SNIP9510.ZIP with some minor typo corrections.
  2463.  
  2464. I am always ready to accept constructive criticism on this
  2465. material, or review requests for the addition of other relevant
  2466. material.  Therefore, if you have questions, comments,
  2467. criticisms, etc. concerning that which has been presented, I
  2468. would greatly appreciate your contacting me using one of the mail
  2469. addresses cited in the Introduction.
  2470.  
  2471.  
  2472.  
  2473.