Free Essay

Tutorial on Pointers and Arrays in C

In: Computers and Technology

Submitted By raman86net
Words 9878
Pages 40
A Tutorial on Pointers and Arrays in C

A TUTORIAL ON POINTERS AND ARRAYS IN C by Ted Jensen Version 1.1 (HTML version) July 1998
This material is hereby placed in the public domain Available in various formats via http://www.netcom.com/~tjensen/ptr/cpoint.htm

TABLE OF CONTENTS
Preface Introduction Chapter 1: What is a Pointer? Chapter 2: Pointer Types and Arrays. Chapter 3: Pointers and Strings Chapter 4: More on Strings Chapter 5: Pointers and Structures Chapter 6: More on Strings and Arrays of Strings Chapter 7: More on Multi-Dimensional Arrays Chapter 8: Pointers to Arrays Chapter 9: Pointers and Dynamic Allocation of Memory Chapter 10: Pointers to Functions

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...orial%20on%20Pointers%20and%20Arrays%20in%20C.htm (1 of 2)3/18/2007 12:09:49 AM

A Tutorial on Pointers and Arrays in C

Epilog

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...orial%20on%20Pointers%20and%20Arrays%20in%20C.htm (2 of 2)3/18/2007 12:09:49 AM

Preface

PREFACE
This document is intended to introduce pointers to beginning programmers in the C programming language. Over several years of reading and contributing to various conferences on C including those on the FidoNet and UseNet, I have noted a large number of newcomers to C appear to have a difficult time in grasping the fundamentals of pointers. I therefore undertook the task of trying to explain them in plain language with lots of examples. The first version of this document was placed in the public domain, as is this one. It was picked up by Bob Stout who included it as a file called PTR-HELP.TXT in his widely distributed collection of SNIPPETS. Since that original 1995 release, I have added a significant amount of material and made some minor corrections in the original work. In this HTML version 1.1 I've made a number of minor changes to the wording as a result of comments emailed to me from around the world.

Acknowledgements:
There are so many people who have unknowingly contributed to this work because of the questions they have posed in the FidoNet C Echo, or the UseNet Newsgroup comp.lang.c, or several other conferences in other networks, that it would be impossible to list them all. Special thanks go to Bob Stout who was kind enough to include the first version of this material in his SNIPPETS file.

About the Author:
Ted Jensen is a retired Electronics Engineer who worked as a hardware designer or manager of hardware designers in the field of magnetic recording. Programming has been a hobby of his off and on since 1968 when he learned how to keypunch cards for submission to be run on a mainframe. (The mainframe had 64K of magnetic core memory!).

Use of this Material:
Everything contained herein is hereby released to the Public Domain. Any person may copy or distribute this material in any manner they wish. The only thing I ask is that if this material is used as a teaching aid in a class, I would appreciate it if it were distributed in its entirety, i.e. including all chapters, the preface and the introduction. I would also appreciate it if, under such circumstances, the instructor of such a class would drop me a note at one of the addresses below informing me of this. I have written this with the hope that it will be useful to others and since I'm not asking any financial remuneration, the only way I know that I have at least partially reached that goal is via feedback from those who find this material useful. file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%20on%20Pointers%20and%20Arrays%20in%20C/Preface.htm (1 of 2)3/18/2007 12:09:49 AM

Preface

By the way, you needn't be an instructor or teacher to contact me. I would appreciate a note from anyone who finds the material useful, or who has constructive criticism to offer. I'm also willing to answer questions submitted by email at the addresses shown below.

Other versions of this document:
In addition to this hypertext version of this document, I have made available other versions more suitable for printing or for downloading of the entire document. If you are interested in keeping up to date on my progress in that area, or want to check for more recent versions of this document, see my Web Site at http://www.netcom.com/~tjensen/ptr/cpoint.htm Ted Jensen Redwood City, California tjensen@ix.netcom.com July 1998 Continue with Pointer Tutorial Back to Table of Contents

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%20on%20Pointers%20and%20Arrays%20in%20C/Preface.htm (2 of 2)3/18/2007 12:09:49 AM

"Introduction"

INTRODUCTION
If you want to be proficient in the writing of code in the C programming language, you must have a thorough working knowledge of how to use pointers. Unfortunately, C pointers appear to represent a stumbling block to newcomers, particularly those coming from other computer languages such as Fortran, Pascal or Basic. To aid those newcomers in the understanding of pointers I have written the following material. To get the maximum benefit from this material, I feel it is important that the user be able to run the code in the various listings contained in the article. I have attempted, therefore, to keep all code ANSI compliant so that it will work with any ANSI compliant compiler. I have also tried to carefully block the code within the text. That way, with the help of an ASCII text editor, you can copy a given block of code to a new file and compile it on your system. I recommend that readers do this as it will help in understanding the material. Continue with Pointer Tutorial Back to Table of Contents

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%20on%20Pointers%20and%20Arrays%20in%20C/Introduction.htm3/18/2007 12:09:50 AM

Chapter 1

CHAPTER 1: What is a pointer?
One of those things beginners in C find difficult is the concept of pointers. The purpose of this tutorial is to provide an introduction to pointers and their use to these beginners. I have found that often the main reason beginners have a problem with pointers is that they have a weak or minimal feeling for variables, (as they are used in C). Thus we start with a discussion of C variables in general. A variable in a program is something with a name, the value of which can vary. The way the compiler and linker handles this is that it assigns a specific block of memory within the computer to hold the value of that variable. The size of that block depends on the range over which the variable is allowed to vary. For example, on PC's the size of an integer variable is 2 bytes, and that of a long integer is 4 bytes. In C the size of a variable type such as an integer need not be the same on all types of machines. When we declare a variable we inform the compiler of two things, the name of the variable and the type of the variable. For example, we declare a variable of type integer with the name k by writing: int k; On seeing the "int" part of this statement the compiler sets aside 2 bytes of memory (on a PC) to hold the value of the integer. It also sets up a symbol table. In that table it adds the symbol k and the relative address in memory where those 2 bytes were set aside. Thus, later if we write: k = 2; we expect that, at run time when this statement is executed, the value 2 will be placed in that memory location reserved for the storage of the value of k. In C we refer to a variable such as the integer k as an "object". In a sense there are two "values" associated with the object k. One is the value of the integer stored there (2 in the above example) and the other the "value" of the memory location, i.e., the address of k. Some texts refer to these two values with the nomenclature rvalue (right value, pronounced "are value") and lvalue (left value, pronounced "el value") respectively. In some languages, the lvalue is the value permitted on the left side of the assignment operator '=' (i.e. the address where the result of evaluation of the right side ends up). The rvalue is that which is on the right side of the assignment statement, the 2 above. Rvalues cannot be used on the left side of the assignment statement. Thus: 2 = k; is illegal. Actually, the above definition of "lvalue" is somewhat modified for C. According to K&R II (page 197): [1] "An object is a named region of storage; an lvalue is an expression referring to an object."

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2001.htm (1 of 4)3/18/2007 12:09:50 AM

Chapter 1

However, at this point, the definition originally cited above is sufficient. As we become more familiar with pointers we will go into more detail on this. Okay, now consider: int j, k; k = 2; j = 7; k = j;

age); }

/* p points to a structure */

-------------------- end of program 5.2 ---------------Again, this is a lot of information to absorb at one time. The reader should compile and run the various code snippets and using a debugger monitor things like my_struct and p while single stepping through the main and following the code down into the function to see what is happening. Continue with Pointer Tutorial Back to Table of Contents

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2005.htm (4 of 4)3/18/2007 12:09:51 AM

Chapter 6

CHAPTER 6: Some more on Strings, and Arrays of Strings
Well, let's go back to strings for a bit. In the following all assignments are to be understood as being global, i.e. made outside of any function, including main(). We pointed out in an earlier chapter that we could write: char my_string[40] = "Ted"; which would allocate space for a 40 byte array and put the string in the first 4 bytes (three for the characters in the quotes and a 4th to handle the terminating '\0'). Actually, if all we wanted to do was store the name "Ted" we could write: char my_name[] = "Ted"; and the compiler would count the characters, leave room for the nul character and store the total of the four characters in memory the location of which would be returned by the array name, in this case my_name. In some code, instead of the above, you might see: char *my_name = "Ted"; which is an alternate approach. Is there a difference between these? The answer is.. yes. Using the array notation 4 bytes of storage in the static memory block are taken up, one for each character and one for the terminating nul character. But, in the pointer notation the same 4 bytes required, plus N bytes to store the pointer variable my_name (where N depends on the system but is usually a minimum of 2 bytes and can be 4 or more). In the array notation, my_name is short for &myname[0] which is the address of the first element of the array. Since the location of the array is fixed during run time, this is a constant (not a variable). In the pointer notation my_name is a variable. As to which is the better method, that depends on what you are going to do within the rest of the program. Let's now go one step further and consider what happens if each of these declarations are done within a function as opposed to globally outside the bounds of any function. void my_function_A(char *ptr) { file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2006.htm (1 of 5)3/18/2007 12:09:51 AM

Chapter 6

char a[] = "ABCDE" . . }

void my_function_B(char *ptr) { char *cp = "FGHIJ" . . } In the case of my_function_A, the content, or value(s), of the array a[] is considered to be the data. The array is said to be initialized to the values ABCDE. In the case of my_function_B, the value of the pointer cp is considered to be the data. The pointer has been initialized to point to the string FGHIJ. In both my_function_A and my_function_B the definitions are local variables and thus the string ABCDE is stored on the stack, as is the value of the pointer cp. The string FGHIJ can be stored anywhere. On my system it gets stored in the data segment. By the way, array initialization of automatic variables as I have done in my_function_A was illegal in the older K&R C and only "came of age" in the newer ANSI C. A fact that may be important when one is considering portability and backwards compatibility. As long as we are discussing the relationship/differences between pointers and arrays, let's move on to multi-dimensional arrays. Consider, for example the array: char multi[5][10]; Just what does this mean? Well, let's consider it in the following light. char multi[5][10]; Let's take the underlined part to be the "name" of an array. Then prepending the char and appending the [10] we have an array of 10 characters. But, the name multi[5] is itself an array indicating that there are 5 elements each being an array of 10 characters. Hence we have an array of 5 arrays of 10 characters each.. Assume we have filled this two dimensional array with data of some kind. In memory, it might look as if it had been formed by initializing 5 separate arrays using something like: multi[0] = {'0','1','2','3','4','5','6','7','8','9'} file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2006.htm (2 of 5)3/18/2007 12:09:51 AM

Chapter 6

multi[1] multi[2] multi[3] multi[4]

= = = =

{'a','b','c','d','e','f','g','h','i','j'} {'A','B','C','D','E','F','G','H','I','J'} {'9','8','7','6','5','4','3','2','1','0'} {'J','I','H','G','F','E','D','C','B','A'}

At the same time, individual elements might be addressable using syntax such as: multi[0][3] = '3' multi[1][7] = 'h' multi[4][0] = 'J' Since arrays are contiguous in memory, our actual memory block for the above should look like: 0123456789abcdefghijABCDEFGHIJ9876543210JIHGFEDCBA ^ |_____ starting at the address &multi[0][0]

Note that I did not write multi[0] = "0123456789". Had I done so a terminating '\0' would have been implied since whenever double quotes are used a '\0' character is appended to the characters contained within those quotes. Had that been the case I would have had to set aside room for 11 characters per row instead of 10. My goal in the above is to illustrate how memory is laid out for 2 dimensional arrays. That is, this is a 2 dimensional array of characters, NOT an array of "strings". Now, the compiler knows how many columns are present in the array so it can interpret multi + 1 as the address of the 'a' in the 2nd row above. That is, it adds 10, the number of columns, to get this location. If we were dealing with integers and an array with the same dimension the compiler would add 10*sizeof (int) which, on my machine, would be 20. Thus, the address of the 9 in the 4th row above would be &multi[3][0] or *(multi + 3) in pointer notation. To get to the content of the 2nd element in the 4th row we add 1 to this address and dereference the result as in *(*(multi + 3) + 1) With a little thought we can see that: *(*(multi + row) + col) multi[row][col] and yield the same results.

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2006.htm (3 of 5)3/18/2007 12:09:51 AM

Chapter 6

The following program illustrates this using integer arrays instead of character arrays. ------------------- program 6.1 ---------------------/* Program 6.1 from PTRTUT10.HTM #include #define ROWS 5 #define COLS 10 int multi[ROWS][COLS]; int main(void) { int row, col; for (row = 0; row < ROWS; row++) { for (col = 0; col < COLS; col++) { multi[row][col] = row*col; } } for (row = 0; row < ROWS; row++) { for (col = 0; col < COLS; col++) { printf("\n%d ",multi[row][col]); printf("%d ",*(*(multi + row) + col)); } } return 0; } ----------------- end of program 6.1 --------------------Because of the double de-referencing required in the pointer version, the name of a 2 dimensional array is often said to be equivalent to a pointer to a pointer. With a three dimensional array we would be dealing with an array of arrays of arrays and some might say its name would be equivalent to a pointer to a pointer to a pointer. However, here we have initially set aside the block of memory for the array by defining it using array notation. Hence, we are dealing with a constant, not a variable. That is we are talking about a fixed address not a variable pointer. The dereferencing function used above permits us to access any element in the array of arrays without the need of changing the value of that address (the file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2006.htm (4 of 5)3/18/2007 12:09:51 AM

6/13/97*/

Chapter 6

address of multi[0][0] as given by the symbol multi). Continue with Pointer Tutorial Back to Table of Contents

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2006.htm (5 of 5)3/18/2007 12:09:51 AM

Chapter 7

CHAPTER 7: More on Multi-Dimensional Arrays
In the previous chapter we noted that given #define ROWS 5 #define COLS 10 int multi[ROWS][COLS]; we can access individual elements of the array multi using either: multi[row][col] or *(*(multi + row) + col) To understand more fully what is going on, let us replace *(multi + row) with X as in: *(X + col) Now, from this we see that X is like a pointer since the expression is de-referenced and we know that col is an integer. Here the arithmetic being used is of a special kind called "pointer arithmetic" is being used. That means that, since we are talking about an integer array, the address pointed to by (i.e. value of) X + col + 1 must be greater than the address X + col by and amount equal to sizeof(int). Since we know the memory layout for 2 dimensional arrays, we can determine that in the expression multi + row as used above, multi + row + 1 must increase by value an amount equal to that needed to "point to" the next row, which in this case would be an amount equal to COLS * sizeof(int). That says that if the expression *(*(multi + row) + col) is to be evaluated correctly at run time, the compiler must generate code which takes into consideration the value of COLS, i.e. the 2nd dimension. Because of the equivalence of the two forms of expression, this is true whether we are using the pointer expression as here or the array expression multi[row][col]. Thus, to evaluate either expression, a total of 5 values must be known: file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2007.htm (1 of 3)3/18/2007 12:09:51 AM

Chapter 7

1. The address of the first element of the array, which is returned by the expression multi, i.e., the name of the array. 2. The size of the type of the elements of the array, in this case sizeof(int). 3. The 2nd dimension of the array 4. The specific index value for the first dimension, row in this case. 5. The specific index value for the second dimension, col in this case. Given all of that, consider the problem of designing a function to manipulate the element values of a previously declared array. For example, one which would set all the elements of the array multi to the value 1. void set_value(int m_array[][COLS]) { int row, col; for (row = 0; row < ROWS; row++) { for (col = 0; col < COLS; col++) { m_array[row][col] = 1; } } }

And to call this function we would then use: set_value(multi); Now, within the function we have used the values #defined by ROWS and COLS that set the limits on the for loops. But, these #defines are just constants as far as the compiler is concerned, i.e. there is nothing to connect them to the array size within the function. row and col are local variables, of course. The formal parameter definition permits the compiler to determine the characteristics associated with the pointer value that will be passed at run time. We really don’t need the first dimension and, as will be seen later, there are occasions where we would prefer not to define it within the parameter definition, out of habit or consistency, I have not used it here. But, the second dimension must be used as has been shown in the expression for the parameter. The reason is that we need this in the evaluation of m_array [row][col] as has been described. While the parameter defines the data type (int in this case) and the automatic variables for row and column are defined in the for loops, only one value can be passed using a single parameter. In this case, that is the value of multi as noted in the call statement, i.e. the address of the first element, often referred to as a pointer to the array. Thus, the only way we have of informing the compiler of the 2nd dimension is by explicitly including it in the parameter definition.

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2007.htm (2 of 3)3/18/2007 12:09:51 AM

Chapter 7

In fact, in general all dimensions of higher order than one are needed when dealing with multidimensional arrays. That is if we are talking about 3 dimensional arrays, the 2nd and 3rd dimension must be specified in the parameter definition. Continue with Pointer Tutorial Back to Table of Contents

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2007.htm (3 of 3)3/18/2007 12:09:51 AM

Chapter 8

CHAPTER 8: Pointers to Arrays
Pointers, of course, can be "pointed at" any type of data object, including arrays. While that was evident when we discussed program 3.1, it is important to expand on how we do this when it comes to multidimensional arrays. To review, in Chapter 2 we stated that given an array of integers we could point an integer pointer at that array using: int *ptr; ptr = &my_array[0];

/* point our pointer at the first integer in our array */

As we stated there, the type of the pointer variable must match the type of the first element of the array. In addition, we can use a pointer as a formal parameter of a function which is designed to manipulate an array. e.g. Given: int array[3] = {'1', '5', '7'}; void a_func(int *p); Some programmers might prefer to write the function prototype as: void a_func(int p[]); which would tend to inform others who might use this function that the function is designed to manipulate the elements of an array. Of course, in either case, what actually gets passed is the value of a pointer to the first element of the array, independent of which notation is used in the function prototype or definition. Note that if the array notation is used, there is no need to pass the actual dimension of the array since we are not passing the whole array, only the address to the first element. We now turn to the problem of the 2 dimensional array. As stated in the last chapter, C interprets a 2 dimensional array as an array of one dimensional arrays. That being the case, the first element of a 2 dimensional array of integers is a one dimensional array of integers. And a pointer to a two dimensional array of integers must be a pointer to that data type. One way of accomplishing this is through the use of the keyword "typedef". typedef assigns a new name to a specified data type. For example: typedef unsigned char byte; file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2008.htm (1 of 2)3/18/2007 12:09:51 AM

Chapter 8

causes the name byte to mean type unsigned char. Hence byte b[10]; would be an array of unsigned characters.

Note that in the typedef declaration, the word byte has replaced that which would normally be the name of our unsigned char. That is, the rule for using typedef is that the new name for the data type is the name used in the definition of the data type. Thus in: typedef int Array[10]; Array becomes a data type for an array of 10 integers. i.e. Array my_arr; declares my_arr as an array of 10 integers and Array arr2d[5]; makes arr2d an array of 5 arrays of 10 integers each. Also note that Array *p1d; makes p1d a pointer to an array of 10 integers. Because *p1d points to the same type as arr2d, assigning the address of the two dimensional array arr2d to p1d, the pointer to a one dimensional array of 10 integers is acceptable. i.e. p1d = &arr2d[0]; or p1d = arr2d; are both correct. Since the data type we use for our pointer is an array of 10 integers we would expect that incrementing p1d by 1 would change its value by 10*sizeof(int), which it does. That is, sizeof(*p1d) is 20. You can prove this to yourself by writing and running a simple short program. Now, while using typedef makes things clearer for the reader and easier on the programmer, it is not really necessary. What we need is a way of declaring a pointer like p1d without the need of the typedef keyword. It turns out that this can be done and that int (*p1d)[10]; is the proper declaration, i.e. p1d here is a pointer to an array of 10 integers just as it was under the declaration using the Array type. Note that this is different from int *p1d[10]; which would make p1d the name of an array of 10 pointers to type int. Continue with Pointer Tutorial Back to Table of Contents

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2008.htm (2 of 2)3/18/2007 12:09:51 AM

Chapter 9

CHAPTER 9: Pointers and Dynamic Allocation of Memory
There are times when it is convenient to allocate memory at run time using malloc(), calloc(), or other allocation functions. Using this approach permits postponing the decision on the size of the memory block need to store an array, for example, until run time. Or it permits using a section of memory for the storage of an array of integers at one point in time, and then when that memory is no longer needed it can be freed up for other uses, such as the storage of an array of structures. When memory is allocated, the allocating function (such as malloc(), calloc(), etc.) returns a pointer. The type of this pointer depends on whether you are using an older K&R compiler or the newer ANSI type compiler. With the older compiler the type of the returned pointer is char, with the ANSI compiler it is void. If you are using an older compiler, and you want to allocate memory for an array of integers you will have to cast the char pointer returned to an integer pointer. For example, to allocate space for 10 integers we might write: int *iptr; iptr = (int *)malloc(10 * sizeof(int)); if (iptr == NULL) { .. ERROR ROUTINE GOES HERE .. } If you are using an ANSI compliant compiler, malloc() returns a void pointer and since a void pointer can be assigned to a pointer variable of any object type, the (int *) cast shown above is not needed. The array dimension can be determined at run time and is not needed at compile time. That is, the 10 above could be a variable read in from a data file or keyboard, or calculated based on some need, at run time. Because of the equivalence between array and pointer notation, once iptr has been assigned as above, one can use the array notation. For example, one could write: int k; for (k = 0; k < 10; k++) iptr[k] = 2; to set the values of all elements to 2. Even with a reasonably good understanding of pointers and arrays, one place the newcomer to C is likely to stumble at first is in the dynamic allocation of multi-dimensional arrays. In general, we would like to be able to access elements of such arrays using array notation, not pointer notation, wherever possible. Depending on the application we may or may not know both dimensions at compile time. This leads to a variety of ways to go about our task. As we have seen, when dynamically allocating a one dimensional array its dimension can be determined at run time. Now, when using dynamic allocation of higher order arrays, we never need to know the first dimension at compile time. Whether we need to know the higher dimensions depends on how we go about writing the code. file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2009.htm (1 of 9)3/18/2007 12:09:51 AM

Chapter 9

Here I will discuss various methods of dynamically allocating room for 2 dimensional arrays of integers. First we will consider cases where the 2nd dimension is known at compile time.

METHOD 1:
One way of dealing with the problem is through the use of the typedef keyword. To allocate a 2 dimensional array of integers recall that the following two notations result in the same object code being generated: multi[row][col] = 1; *(*(multi + row) + col) = 1;

It is also true that the following two notations generate the same code: multi[row] *(multi + row)

Since the one on the right must evaluate to a pointer, the array notation on the left must also evaluate to a pointer. In fact multi[0] will return a pointer to the first integer in the first row, multi[1] a pointer to the first integer of the second row, etc. Actually, multi[n] evaluates to a pointer to that array of integers that make up the n-th row of our 2 dimensional array. That is, multi can be thought of as an array of arrays and multi[n] as a pointer to the n-th array of this array of arrays. Here the word pointer is being used to represent an address value. While such usage is common in the literature, when reading such statements one must be careful to distinguish between the constant address of an array and a variable pointer which is a data object in itself. Consider now: --------------- Program 9.1 -------------------------------/* Program 9.1 from PTRTUT10.HTM #include #include #define COLS 5 typedef int RowArray[COLS]; RowArray *rptr; int main(void) { int nrows = 10; int row, col; rptr = malloc(nrows * COLS * sizeof(int)); for (row = 0; row < nrows; row++) file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2009.htm (2 of 9)3/18/2007 12:09:51 AM

6/13/97 */

Chapter 9

{ for (col = 0; col < COLS; col++) { rptr[row][col] = 17; } } return 0; } ------------- End of Prog. 9.1 --------------------------------

Here I have assumed an ANSI compiler so a cast on the void pointer returned by malloc() is not required. If you are using an older K&R compiler you will have to cast using: rptr = (RowArray *)malloc(.... etc. Using this approach, rptr has all the characteristics of an array name name, (except that rptr is modifiable), and array notation may be used throughout the rest of the program. That also means that if you intend to write a function to modify the array contents, you must use COLS as a part of the formal parameter in that function, just as we did when discussing the passing of two dimensional arrays to a function.

METHOD 2:
In the METHOD 1 above, rptr turned out to be a pointer to type "one dimensional array of COLS integers". It turns out that there is syntax which can be used for this type without the need of typedef. If we write: int (*xptr)[COLS];

the variable xptr will have all the same characteristics as the variable rptr in METHOD 1 above, and we need not use the typedef keyword. Here xptr is a pointer to an array of integers and the size of that array is given by the #defined COLS. The parenthesis placement makes the pointer notation predominate, even though the array notation has higher precedence. i.e. had we written int *xptr[COLS]; we would have defined xptr as an array of pointers holding the number of pointers equal to that #defined by COLS. That is not the same thing at all. However, arrays of pointers have their use in the dynamic allocation of two dimensional arrays, as will be seen in the next 2 methods.

METHOD 3:
Consider the case where we do not know the number of elements in each row at compile time, i.e. both the number of rows and number of columns must be determined at run time. One way of doing this would be to file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2009.htm (3 of 9)3/18/2007 12:09:51 AM

Chapter 9

create an array of pointers to type int and then allocate space for each row and point these pointers at each row. Consider: -------------- Program 9.2 -----------------------------------/* Program 9.2 from PTRTUT10.HTM #include #include int main(void) { int nrows = 5; /* Both nrows and ncols could be evaluated */ int ncols = 10; /* or read in at run time */ int row; int **rowptr; rowptr = malloc(nrows * sizeof(int *)); if (rowptr == NULL) { puts("\nFailure to allocate room for row pointers.\n"); exit(0); } printf("\n\n\nIndex Pointer(hex) Pointer(dec) Diff.(dec)"); 6/13/97 */

for (row = 0; row < nrows; row++) { rowptr[row] = malloc(ncols * sizeof(int)); if (rowptr[row] == NULL) { printf("\nFailure to allocate for row[%d]\n",row); exit(0); } printf("\n%d %p %d", row, rowptr[row], rowptr[row]); if (row > 0) printf(" %d",(int)(rowptr[row] - rowptr[row-1])); } return 0; } --------------- End 9.2 ------------------------------------

In the above code rowptr is a pointer to pointer to type int. In this case it points to the first element of an array of pointers to type int. Consider the number of calls to malloc(): file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2009.htm (4 of 9)3/18/2007 12:09:51 AM

Chapter 9

To get the array of pointers To get space for the rows Total

1 5 ----6

call calls calls

If you choose to use this approach note that while you can use the array notation to access individual elements of the array, e.g. rowptr[row][col] = 17;, it does not mean that the data in the "two dimensional array" is contiguous in memory. You can, however, use the array notation just as if it were a continuous block of memory. For example, you can write: rowptr[row][col] = 176; just as if rowptr were the name of a two dimensional array created at compile time. Of course row and col must be within the bounds of the array you have created, just as with an array created at compile time. If you want to have a contiguous block of memory dedicated to the storage of the elements in the array you can do it as follows:

METHOD 4:
In this method we allocate a block of memory to hold the whole array first. We then create an array of pointers to point to each row. Thus even though the array of pointers is being used, the actual array in memory is contiguous. The code looks like this: ----------------- Program 9.3 ----------------------------------/* Program 9.3 from PTRTUT10.HTM #include #include int main(void) { int **rptr; int *aptr; int *testptr; int k; int nrows = 5; int ncols = 8; int row, col; 6/13/97 */

/* Both nrows and ncols could be evaluated */ /* or read in at run time */

/* we now allocate the memory for the array */

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2009.htm (5 of 9)3/18/2007 12:09:51 AM

Chapter 9

aptr = malloc(nrows * ncols * sizeof(int)); if (aptr == NULL) { puts("\nFailure to allocate room for the array"); exit(0); } /* next we allocate room for the pointers to the rows */ rptr = malloc(nrows * sizeof(int *)); if (rptr == NULL) { puts("\nFailure to allocate room for pointers"); exit(0); } /* and now we 'point' the pointers */ for (k = 0; k < nrows; k++) { rptr[k] = aptr + (k * ncols); } /* Now we illustrate how the row pointers are incremented */ printf("\n\nIllustrating how row pointers are incremented"); printf("\n\nIndex Pointer(hex) Diff.(dec)"); for (row = 0; row < nrows; row++) { printf("\n%d %p", row, rptr[row]); if (row > 0) printf(" %d",(rptr[row] - rptr[row-1])); } printf("\n\nAnd now we print out the array\n"); for (row = 0; row < nrows; row++) { for (col = 0; col < ncols; col++) { rptr[row][col] = row + col; printf("%d ", rptr[row][col]); } putchar('\n'); } puts("\n"); /* and here we illustrate that we are, in fact, dealing with file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2009.htm (6 of 9)3/18/2007 12:09:51 AM

Chapter 9

a 2 dimensional array in a contiguous block of memory. */ printf("And now we demonstrate that they are contiguous in memory\n"); testptr = aptr; for (row = 0; row < nrows; row++) { for (col = 0; col < ncols; col++) { printf("%d ", *(testptr++)); } putchar('\n'); } return 0; }

------------- End Program 9.3 -----------------

Consider again, the number of calls to malloc() To get room for the array itself To get room for the array of ptrs Total 1 1 ---2 call call calls

Now, each call to malloc() creates additional space overhead since malloc() is generally implemented by the operating system forming a linked list which contains data concerning the size of the block. But, more importantly, with large arrays (several hundred rows) keeping track of what needs to be freed when the time comes can be more cumbersome. This, combined with the contiguousness of the data block that permits initialization to all zeroes using memset() would seem to make the second alternative the preferred one. As a final example on multidimensional arrays we will illustrate the dynamic allocation of a three dimensional array. This example will illustrate one more thing to watch when doing this kind of allocation. For reasons cited above we will use the approach outlined in alternative two. Consider the following code: ------------------- Program 9.4 ------------------------------------/* Program 9.4 from PTRTUT10.HTM #include #include file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2009.htm (7 of 9)3/18/2007 12:09:51 AM

6/13/97 */

Chapter 9

#include int X_DIM=16; int Y_DIM=5; int Z_DIM=3; int main(void) { char *space; char ***Arr3D; int y, z; ptrdiff_t diff; /* first we set aside space for the array itself */ space = malloc(X_DIM * Y_DIM * Z_DIM * sizeof(char)); /* next we allocate space of an array of pointers, each to eventually point to the first element of a 2 dimensional array of pointers to pointers */ Arr3D = malloc(Z_DIM * sizeof(char **)); /* and for each of these we assign a pointer to a newly allocated array of pointers to a row */ for (z = 0; z < Z_DIM; z++) { Arr3D[z] = malloc(Y_DIM * sizeof(char *)); /* and for each space in this array we put a pointer to the first element of each row in the array space originally allocated */ for (y = 0; y < Y_DIM; y++) { Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM); } } /* And, now we check each address in our 3D array to see if the indexing of the Arr3d pointer leads through in a continuous manner */ for (z = 0; z < Z_DIM; z++) { printf("Location of array %d is %p\n", z, *Arr3D[z]); file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2009.htm (8 of 9)3/18/2007 12:09:51 AM

Chapter 9

for ( y = 0; y < Y_DIM; y++) { printf(" Array %d and Row %d starts at %p", z, y, Arr3D[z][y]); diff = Arr3D[z][y] - space; printf(" diff = %d ",diff); printf(" z = %d y = %d\n", z, y); } } return 0; } ------------------- End of Prog. 9.4 ----------------------------

If you have followed this tutorial up to this point you should have no problem deciphering the above on the basis of the comments alone. There are a couple of points that should be made however. Let's start with the line which reads: Arr3D[z][y] = space + (z*(X_DIM * Y_DIM) + y*X_DIM); Note that here space is a character pointer, which is the same type as Arr3D[z][y]. It is important that when adding an integer, such as that obtained by evaluation of the expression (z*(X_DIM * Y_DIM) + y*X_DIM), to a pointer, the result is a new pointer value. And when assigning pointer values to pointer variables the data types of the value and variable must match. Continue with Pointer Tutorial Back to Table of Contents

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2009.htm (9 of 9)3/18/2007 12:09:51 AM

Chapter10

CHAPTER 10: Pointers to Functions
Up to this point we have been discussing pointers to data objects. C also permits the declaration of pointers to functions. Pointers to functions have a variety of uses and some of them will be discussed here. Consider the following real problem. You want to write a function that is capable of sorting virtually any collection of data that can be stored in an array. This might be an array of strings, or integers, or floats, or even structures. The sorting algorithm can be the same for all. For example, it could be a simple bubble sort algorithm, or the more complex shell or quick sort algorithm. We'll use a simple bubble sort for demonstration purposes. Sedgewick [1] has described the bubble sort using C code by setting up a function which when passed a pointer to the array would sort it. If we call that function bubble(), a sort program is described by bubble_1.c, which follows: /*-------------------- bubble_1.c --------------------*/ /* Program bubble_1.c from PTRTUT10.HTM #include int arr[10] = { 3,6,1,2,3,8,4,1,7,2}; void bubble(int a[], int N); int main(void) { int i; putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } bubble(arr,10); putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0; } 6/13/97 */

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2010.htm (1 of 13)3/18/2007 12:09:52 AM

Chapter10

void bubble(int a[], int N) { int i, j, t; for (i = N-1; i >= 0; i--) { for (j = 1; j a[j]) { t = a[j-1]; a[j-1] = a[j]; a[j] = t; } } } }

/*---------------------- end bubble_1.c -----------------------*/

The bubble sort is one of the simpler sorts. The algorithm scans the array from the second to the last element comparing each element with the one which precedes it. If the one that precedes it is larger than the current element, the two are swapped so the larger one is closer to the end of the array. On the first pass, this results in the largest element ending up at the end of the array. The array is now limited to all elements except the last and the process repeated. This puts the next largest element at a point preceding the largest element. The process is repeated for a number of times equal to the number of elements minus 1. The end result is a sorted array. Here our function is designed to sort an array of integers. Thus in line 1 we are comparing integers and in lines 2 through 4 we are using temporary integer storage to store integers. What we want to do now is see if we can convert this code so we can use any data type, i.e. not be restricted to integers. At the same time we don't want to have to analyze our algorithm and the code associated with it each time we use it. We start by removing the comparison from within the function bubble() so as to make it relatively easy to modify the comparison function without having to re-write portions related to the actual algorithm. This results in bubble_2.c: /*---------------------- bubble_2.c -------------------------*/ /* Program bubble_2.c from PTRTUT10.HTM 6/13/97 */

/* Separating the comparison function */

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2010.htm (2 of 13)3/18/2007 12:09:52 AM

Chapter10

#include int arr[10] = { 3,6,1,2,3,8,4,1,7,2}; void bubble(int a[], int N); int compare(int m, int n); int main(void) { int i; putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } bubble(arr,10); putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0; } void bubble(int a[], int N) { int i, j, t; for (i = N-1; i >= 0; i--) { for (j = 1; j n); } /*--------------------- end of bubble_2.c -----------------------*/ If our goal is to make our sort routine data type independent, one way of doing this is to use pointers to type void to point to the data instead of using the integer data type. As a start in that direction let's modify a few things in the above so that pointers can be used. To begin with, we'll stick with pointers to type integer. /*----------------------- bubble_3.c -------------------------*/ /* Program bubble_3.c from PTRTUT10.HTM #include int arr[10] = { 3,6,1,2,3,8,4,1,7,2}; void bubble(int *p, int N); int compare(int *m, int *n); int main(void) { int i; putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } bubble(arr,10); putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0; } void bubble(int *p, int N) { int i, j, t; for (i = N-1; i >= 0; i--) { for (j = 1; j *n); } /*------------------ end of bubble3.c -------------------------*/

Note the changes. We are now passing a pointer to an integer (or array of integers) to bubble(). And from within bubble we are passing pointers to the elements of the array that we want to compare to our comparison function. And, of course we are dereferencing these pointer in our compare() function in order to make the actual comparison. Our next step will be to convert the pointers in bubble() to pointers to type void so that that function will become more type insensitive. This is shown in bubble_4. /*------------------ bubble_4.c ----------------------------*/ /* Program bubble_4.c from PTRTUT10,HTM #include int arr[10] = { 3,6,1,2,3,8,4,1,7,2}; void bubble(int *p, int N); int compare(void *m, void *n); int main(void) { int i; putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } bubble(arr,10); file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2010.htm (5 of 13)3/18/2007 12:09:52 AM

6/13/97 */

Chapter10

putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0; } void bubble(int *p, int N) { int i, j, t; for (i = N-1; i >= 0; i--) { for (j = 1; j *n1); } /*------------------ end of bubble_4.c ---------------------*/

Note that, in doing this, in compare() we had to introduce the casting of the void pointer types passed to the actual type being sorted. But, as we'll see later that's okay. And since what is being passed to bubble() is still a pointer to an array of integers, we had to cast these pointers to void pointers when we passed them as parameters in our call to compare(). We now address the problem of what we pass to bubble(). We want to make the first parameter of that function a void pointer also. But, that means that within bubble() we need to do something about the variable t, which is currently an integer. Also, where we use t = p[j-1]; the type of p[j-1] needs to be known in order file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2010.htm (6 of 13)3/18/2007 12:09:52 AM

Chapter10

to know how many bytes to copy to the variable t (or whatever we replace t with). Currently, in bubble_4.c, knowledge within bubble() as to the type of the data being sorted (and hence the size of each individual element) is obtained from the fact that the first parameter is a pointer to type integer. If we are going to be able to use bubble() to sort any type of data, we need to make that pointer a pointer to type void. But, in doing so we are going to lose information concerning the size of individual elements within the array. So, in bubble_5.c we will add a separate parameter to handle this size information. These changes, from bubble4.c to bubble5.c are, perhaps, a bit more extensive than those we have made in the past. So, compare the two modules carefully for differences. /*---------------------- bubble5.c ---------------------------*/ /* Program bubble_5.c from PTRTUT10.HTM 6/13/97 */

#include #include long arr[10] = { 3,6,1,2,3,8,4,1,7,2}; void bubble(void *p, size_t width, int N); int compare(void *m, void *n); int main(void) { int i; putchar('\n'); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } bubble(arr, sizeof(long), 10); putchar('\n'); for (i = 0; i < 10; i++) { printf("%ld ", arr[i]); } return 0; }

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2010.htm (7 of 13)3/18/2007 12:09:52 AM

Chapter10

void bubble(void *p, size_t width, int N) { int i, j; unsigned char buf[4]; unsigned char *bp = p; for (i = N-1; i >= 0; i--) { for (j = 1; j *n1); } /*--------------------- end of bubble5.c ---------------------*/

Note that I have changed the data type of the array from int to long to illustrate the changes needed in the compare() function. Within bubble() I've done away with the variable t (which we would have had to change from type int to type long). I have added a buffer of size 4 unsigned characters, which is the size needed to hold a long (this will change again in future modifications to this code). The unsigned character pointer *bp is used to point to the base of the array to be sorted, i.e. to the first element of that array. We also had to modify what we passed to compare(), and how we do the swapping of elements that the comparison indicates need swapping. Use of memcpy() and pointer notation instead of array notation work towards this reduction in type sensitivity.

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2010.htm (8 of 13)3/18/2007 12:09:52 AM

Chapter10

Again, making a careful comparison of bubble5.c with bubble4.c can result in improved understanding of what is happening and why. We move now to bubble6.c where we use the same function bubble() that we used in bubble5.c to sort strings instead of long integers. Of course we have to change the comparison function since the means by which strings are compared is different from that by which long integers are compared. And,in bubble6.c we have deleted the lines within bubble() that were commented out in bubble5.c. /*--------------------- bubble6.c ---------------------*/ /* Program bubble_6.c from PTRTUT10.HTM 6/13/97 */ #include #include #define MAX_BUF 256 char arr2[5][20] = { "Mickey Mouse", "Donald Duck", "Minnie Mouse", "Goofy", "Ted Jensen" }; void bubble(void *p, int width, int N); int compare(void *m, void *n); int main(void) { int i; putchar('\n'); for (i = 0; i < 5; i++) { printf("%s\n", arr2[i]); } bubble(arr2, 20, 5); putchar('\n\n'); for (i = 0; i < 5; i++) { printf("%s\n", arr2[i]); } file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%...Pointers%20and%20Arrays%20in%20C/Chapter%2010.htm (9 of 13)3/18/2007 12:09:52 AM

Chapter10

return 0; } void bubble(void *p, int width, int N) { int i, j, k; unsigned char buf[MAX_BUF]; unsigned char *bp = p; for (i = N-1; i >= 0; i--) { for (j = 1; j 0) { memcpy(buf, bp + width*(j-1), width); memcpy(bp + width*(j-1), bp + j*width , width); memcpy(bp + j*width, buf, width); } } } } int compare(void *m, void *n) { char *m1 = m; char *n1 = n; return (strcmp(m1,n1)); } /*------------------- end of bubble6.c ---------------------*/

But, the fact that bubble() was unchanged from that used in bubble5.c indicates that that function is capable of sorting a wide variety of data types. What is left to do is to pass to bubble() the name of the comparison function we want to use so that it can be truly universal. Just as the name of an array is the address of the first element of the array in the data segment, the name of a function decays into the address of that function in the code segment. Thus we need to use a pointer to a function. In this case the comparison function. Pointers to functions must match the functions pointed to in the number and types of the parameters and the type of the return value. In our case, we declare our function pointer as: int (*fptr)(const void *p1, const void *p2);

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial...ointers%20and%20Arrays%20in%20C/Chapter%2010.htm (10 of 13)3/18/2007 12:09:52 AM

Chapter10

Note that were we to write: int *fptr(const void *p1, const void *p2); we would have a function prototype for a function which returned a pointer to type int. That is because in C the parenthesis () operator have a higher precedence than the pointer * operator. By putting the parenthesis around the string (*fptr) we indicate that we are declaring a function pointer. We now modify our declaration of bubble() by adding, as its 4th parameter, a function pointer of the proper type. It's function prototype becomes: void bubble(void *p, int width, int N, int(*fptr)(const void *, const void *)); When we call the bubble(), we insert the name of the comparison function that we want to use. bubble7.c illustrate how this approach permits the use of the same bubble() function for sorting different types of data. /*------------------- bubble7.c ------------------*/ /* Program bubble_7.c from PTRTUT10.HTM #include #include #define MAX_BUF 256 long arr[10] = { 3,6,1,2,3,8,4,1,7,2}; char arr2[5][20] = { "Mickey Mouse", "Donald Duck", "Minnie Mouse", "Goofy", "Ted Jensen" }; void bubble(void *p, int width, int N, int(*fptr)(const void *, const void *)); int compare_string(const void *m, const void *n); int compare_long(const void *m, const void *n); int main(void) { int i; puts("\nBefore Sorting:\n"); for (i = 0; i < 10; i++) { /* show the long ints */ 6/10/97 */

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial...ointers%20and%20Arrays%20in%20C/Chapter%2010.htm (11 of 13)3/18/2007 12:09:52 AM

Chapter10

printf("%ld ",arr[i]); } puts("\n"); for (i = 0; i < 5; i++) { printf("%s\n", arr2[i]); } bubble(arr, 4, 10, compare_long); bubble(arr2, 20, 5, compare_string); puts("\n\nAfter Sorting:\n"); for (i = 0; i < 10; i++) { printf("%d ",arr[i]); } puts("\n"); for (i = 0; i < 5; i++) { printf("%s\n", arr2[i]); } return 0; } void bubble(void *p, int width, int N, int(*fptr)(const void *, const void *)) { int i, j, k; unsigned char buf[MAX_BUF]; unsigned char *bp = p; for (i = N-1; i >= 0; i--) { for (j = 1; j 0) { memcpy(buf, bp + width*(j-1), width); memcpy(bp + width*(j-1), bp + j*width , width); memcpy(bp + j*width, buf, width); } } } file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial...ointers%20and%20Arrays%20in%20C/Chapter%2010.htm (12 of 13)3/18/2007 12:09:52 AM

/* show the strings */

/* sort the longs */ /* sort the strings */

/* show the sorted longs */

/* show the sorted strings */

Chapter10

} int compare_string(const void *m, const void *n) { char *m1 = (char *)m; char *n1 = (char *)n; return (strcmp(m1,n1)); } int compare_long(const void *m, const void *n) { long *m1, *n1; m1 = (long *)m; n1 = (long *)n; return (*m1 > *n1); } /*----------------- end of bubble7.c -----------------*/

References for Chapter 10:
1. "Algorithms in C" Robert Sedgewick Addison-Wesley ISBN 0-201-51425-7 Continue with Pointer Tutorial Back to Table of Contents

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial...ointers%20and%20Arrays%20in%20C/Chapter%2010.htm (13 of 13)3/18/2007 12:09:52 AM

Epilog

EPILOG
I have written the preceding material to provide an introduction to pointers for newcomers to C. In C, the more one understands about pointers the greater flexibility one has in the writing of code. The above expands on my first effort at this which was entitled ptr_help.txt and found in an early version of Bob Stout's collection of C code SNIPPETS. The content in this version has been updated from that in PTRTUTOT.ZIP included in SNIP9510.ZIP. I am always ready to accept constructive criticism on this material, or review requests for the addition of other relevant material. Therefore, if you have questions, comments, criticisms, etc. concerning that which has been presented, I would greatly appreciate your contacting me via email me at tjensen@ix. netcom.com. Back to Table of Contents

file:///E|/My%20eBooks/_ESSENTIALS_/A%20Tutorial%20on%20Pointers%20and%20Arrays%20in%20C/Epilog.htm3/18/2007 12:09:52 AM…...

Similar Documents

Free Essay

C++ Language

...cplusplus.com C++ Language Tutorial Written by: Juan Soulié Last revision: June, 2007 Available online at: http://www.cplusplus.com/doc/tutorial/ The online version is constantly revised and may contain corrections and changes The C++ Language Tutorial This document and its content is copyright of cplusplus.com © cplusplus.com, 2008. All rights reserved. Any redistribution or reproduction of part or all of the content in any form is prohibited other than to print a personal copy of the entire document or download it to a local hard disk, without modifying its content in any way (including, but not limited to, this copyright notice). You may not, except with express written permission from cplusplus.com, distribute the content of this document. Nor may you transmit it or store it in any other website or other form of electronic retrieval system. 2 © cplusplus.com 2008. All rights reserved The C++ Language Tutorial Table of contents Table of contents ...............................................................................................................................3 Introduction ......................................................................................................................................5 Instructions for use ................................................................................................................................... 5 Basics of C++ .............................................................

Words: 798 - Pages: 4

Free Essay

Arrays

...button was assign to repaint() method. When we click the “Press here” button, It updates the window. There is also a counting that counts how many times we repaint the applet. Code: RoundRectDemo Explanation: As what we have seen, this illustrates how we draw a rectangle into circle. Its uses 6 parameters as the x and y location, the height and the width, and the point how it bends. In this output the increment of the points was 20, until the last number was 80 in which we draw a circle. TADAAA Code: SetFontDemo Explanation: This output is same as the Code DrawStingDemo.java but sets the font to Verdana, Bold, and size 26. Code: DrawPolyDemo Explanation: As what we seen above, we draw a Polygon that has 5 sides. We use an array that has 6 elements that assigns the point and location of our polygon. Following codes may explain: int xPoints[] = {5, 25, 50, 30, 15, 5}; int yPoints[] = {10, 35, 20, 65, 40, 10}; Code: RectangleDemo Explanation: The method used for this output was fillRect() and clearRect(). As what you have seen in the output. The fillRect() is the Rectangle inside the Rectangle and the clearRect() was the Rectangle outside the Rectangle inside the Rectangle or what we called the Rectangle. Code: SetColorDemo Explanation: This is same as the Code SetFontDemo.java but in this case, the Color of the font was changed to Blue but the I think I don’t know why the background that had been set yellow wouldn’t appear....

Words: 359 - Pages: 2

Free Essay

Arrays

...CHAPTER 5 – ARRAYS CASE STUDY SCENARIO Sorting Data A dozen umbrellas lie on the ground just inside the classroom door when Dr. Taylor begins his lecture. “A cold, rainy day like today makes me want to stay in and order pizza for delivery rather than go out myself.” Handing a phone book to a student in the front row, Dr. Taylor says “Gail, please look up the phone number for Domino’s Pizza on Main Street, and if you don’t mind, I will time how long it takes you to find the number.” Gail flips through a few pages while Dr. Taylor looks at his watch. “Here it is . . . 555-8275,” she says. “Seven seconds. Thank you Gail.” Dr. Taylor presses some keys on his cell phone while continuing his conversation. “Now please look up the name of the person with the phone number 555-5982, and again I will time you.” Dr. Taylor’s focus returns to his watch even as he speaks into the phone. Gail slowly flips a couple of pages, then stops just about the same time Dr. Taylor ends his call. “I assure you the number is in there, Gail. We will wait while you look it up.” “You will probably wait a long time,” she says, “because there is no fast way to find a number.” “Why not? It’s the same data.” “But the phone book is sorted by names, so finding a name is easy. Finding a number is very difficult because a phone book is not sorted by numbers.” Dr. Taylor takes the phone book from Gail. “Exactly! The sorting process does not change the data, but it organizes the data in a......

Words: 5653 - Pages: 23

Free Essay

Array

...and their state of residence. The program will display the average age of all family members input, and also display the names of any family members that live in Texas. We will create three separate arrays; one for the names of the family members, another for their ages, and the third will be for their state of residence. We'll first ask the user to enter the number of family members he has (we will limit this to a max of 25); this will allow us to determine how large of arrays we will need to create to store the data. We'll call this variable Size. After inputting all names, ages, and states of residence the data will all be stored within the arrays. The program will identify those family members who reside in Texas, and also display their names on the screen. This will be done by creating a loop that will review all the entries from the names and residencies arrays, compare the state to the string "Texas," and print that corresponding name. The average age will be calculated by also looping through the values in the age array, calculating the collective sum, then (as stated earlier) dividing by Size. Necessary Calculations The variable AvgAge (declared as Float) will be used in order to calculate the average age. A loop will go through each value of the Ages array, keep a running total sum, then divide that total by the variable Size to get the average age. //NOTE: I use Float instead of Integer because there is a possibility of losing a trailing decimal if......

Words: 617 - Pages: 3

Premium Essay

Comparison of C, C++, and C#

...Jason Latham Comparison of C, C++, and C# IADT Seattle The C family of languages has been a cornerstone in the programming field for years. So exactly what is the C family? It includes the C, C++ and C# (pronounced sharp) languages. Now that we know what they are, what are the differences between the three? Well, that is what will be discussed here. C is a minimalistic programming language because it could be compiled in a straightforward manner by a relatively simple compiler. C offers low-level access to memory via pointers and the ability to access specific hardware addresses. C generates only a few instructions of machine languages for each of its core language elements and does not require extensive run-time support. It can be concluded that C language is suitable for many systems-programming applications that had traditionally been implemented in assembly languages (Gabb, 2012). With its inherent low-level memory access and small run-time support, using C for embedded hardware systems is ideal. Many devices such as robots, machinery, and electronic tools are programmed utilizing its ability to access specific hardware addresses. However, as C is structured oriented programming language and focuses on the procedural programming paradigm, it is relatively hard to control the large-scale program. As C language has high level and machine level mixed programming capacity, it is used in most hardware related applications. It is very suitable for writing programs in......

Words: 1038 - Pages: 5

Free Essay

Array

...Nouns | | Verbs | | | | | | Program | Hours | Design | | Arrays | Data | Uses | | People | | Hold | | Integers | | Worked | | Subscripts | | Relate | | Numbers | | Stored | | Pay | | Ask | | wages | | Entered | | hours | | display | | Word Analysis Variable Chart Input | Interim | Output | hours | [index] | wages | empId | | | payRate | | | | | | | | | | | | Major Task List 1. Input hours, employee id numbers, and payrates 2. Create arrays 3. Calculate wages to employee 4. Display results Structure Chart Main Main Psuedo Code PROGRAM Employees AUTHOR Stuart Marlar COURSE COP1000 FUNCTION main (void) RETURNING int BEGIN main Declare Integer Index Declare Integer Array empId[7] = (56588, 45201, 78951, 87775, 84512, 13028, 75804) Declare Double Array hours[7] = (0) Declare Double Array payRate[7] = (0) Declare Double Array wages[7] = (0) FOR index = 0 TO 7 - 1 STEP 1 DO OUTPUT "Employee ID" empId[index] REPEAT OUTPUT "Enter hours" INPUT hours[index] IF hours[index] OUTPUT"Hours cannot be negative" END-IF WHILE hour[index] < 0 ...

Words: 422 - Pages: 2

Premium Essay

Practical Verification & Safeguard Tools for C/C++

...P ra c t i c a l ve ri f i c a t i o n & s a fe g u a rd tools for C/C++ F Michaud . R. Carbone DRDC Valcartier Defence R&D Canada – Valcartier Technical Report DRDC Valcartier TR 2006-735 November 2007 Practical verification & safeguard tools for C/C++ F. Michaud R. Carbone DRDC Valcartier DRDC Valcartier Technical Report DRDC Valcartier TR 2006-735 November 2007 Principal Author Approved by Yves van Chestein Head/IKM Approved for release by Christian Carrier Chief Scientist c Her Majesty the Queen in Right of Canada as represented by the Minister of National Defence, 2007 c Sa Majest´ la Reine (en droit du Canada), telle que repr´sent´e par le ministre de la e e e D´fense nationale, 2007 e Abstract This document is the final report of an activity that took place in 2005-2006. The goal of this project was first to identify common software defects related to the use of the C and C++ programming languages. Errors and vulnerabilities created by these defects were also investigated, so that meaningful test cases could be created for the evaluation of best-ofbreed automatic verification tools. Finally, when relevant, best practices were inferred from our experiments with these tools. ´ ´ Resume Ce document est le rapport final d’un projet de recherche qui a eu lieu en 2005-2006. Le but de ce projet ´tait avant tout d’identifier les d´fauts logiciels courants li´s ` l’utilisation des e e e a langages de programmation C et C++. Les erreurs et......

Words: 22394 - Pages: 90

Free Essay

C# Array

...Background Information: * Array is a list of data items that all have the same data type and the same name * Each item in the array is called an element . * Each element has an index. Beginning index is 0 Example 1: Suppose we would like to store the scores of 4 students in a classroom // create an array called scores whose size is 4 and stores numbers of type double double[ ] scores= new double[4]; //Assign values to the elements of the array . scores [0]=90; scores[1]= 95; scores [2]=70; scores[3]= 60; 90 | 95 | 70 | 60 | scores [0] scores [1] scores [2] scores [3] Example 2: You can also assign values to array elements using an Initializer list: // create an double array called scores and fill it with the 4 test scores 90, 95, 70, 60 double[ ] scores = {90, 95, 70, 60}; 90 | 95 | 70 | 60 | scores [0] scores [1] scores [2] scores [3] * Write code to display the value of the third element in a label: lblOutput.Text = scores[2].ToString(); * write a line of code to get the length of the array int size = scores.Length; // size is 4 Exercise 1 Code | | string[] letters = {“A”,”B”};int size = letters.Length; | What is the value of size ?What is stored in letters[1] ? | Exercise 2 Code | | int[] numbers = {10,20,30};int size = numbers.Length; | What is the value of size ?What is the value of : numbers[0] + numbers[1] + numbers[2]......

Words: 497 - Pages: 2

Free Essay

C++ Objects Solutions

...C++ LOCATION OF VIDEONOTES IN THE TEXT Chapter 1 Designing a Program with Pseudocode, p. 19 Designing the Account Balance Program, p. 24 Predicting the Output of Problem 30, p. 24 Solving the Candy Bar Sales Problem, p. 25 Using cout to Display Output, p. 32 Assignment Statements, p. 59 Arithmetic Operators, p. 61 Solving the Restaurant Bill Problem, p. 72 Using cin to Read Input, p. 75 Evaluating Mathematical Expressions, p. 81 Combined Assignment Operators, p. 102 Solving the Stadium Seating Problem, p. 151 Using an if Statement, p. 162 Using an if/else Statement, p. 172 Using an if/else if Statement, p. 175 Solving the Time Calculator Problem, p. 236 The while Loop, p. 249 The for Loop, p. 263 Nested Loops, p. 277 Solving the Ocean Levels Problem, p. 299 Defining and Calling Functions, p. 306 Using Function Arguments, p. 316 Value-Returning Functions, p. 326 Solving the Markup Problem, p. 380 Creating a Class, p. 391 Creating and Using Class Objects, p. 393 Creating and Using Structures, p. 436 Solving the Car Class Problem, p. 480 Accessing Array Elements, p. 487 Passing an Array to a Function, p. 517 Two-Dimensional Arrays, p. 526 Solving the Chips and Salsa Problem, p. 567 Performing a Binary Search, p. 580 Sorting a Set of Data, p. 587 Solving the Lottery Winners Problem, p. 616 (continued on next page) Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 LOCATION OF VIDEONOTES IN THE TEXT Chapter 10 Pointer......

Words: 11246 - Pages: 45

Premium Essay

C Tutorial

...C Programming Tutorial C PROGRAMMING TUTORIAL Simply Easy Learning by tutorialspoint.com tutorialspoint.com i COPYRIGHT & DISCLAIMER NOTICE  All the content and graphics on this tutorial are the property of tutorialspoint.com. Any content from tutorialspoint.com or this tutorial may not be redistributed or reproduced in any way, shape, or form without the written permission of tutorialspoint.com. Failure to do so is a violation of copyright laws. This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the accuracy of the site or its contents including this tutorial. If you discover that the tutorialspoint.com site or this tutorial content contains some errors, please contact us at webmaster@tutorialspoint.com ii T able of Contents C Language Overview .............................................................. 1 Facts about C ............................................................................................... 1 Why to use C ? ............................................................................................. 2 C Programs .................................................................................................. 2 C Environment Setup ............................................................... 3 Text Editor ................................................................................................... 3 The C Compiler ................................................

Words: 14106 - Pages: 57

Free Essay

Java Array

...Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables. Declaring Array Variables: To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable: ------------------------------------------------- dataType[] arrayRefVar; // preferred way. ------------------------------------------------- ------------------------------------------------- or ------------------------------------------------- ------------------------------------------------- dataType arrayRefVar[]; // works but not preferred way. Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers. Example: The following code snippets are...

Words: 1665 - Pages: 7

Free Essay

C Language

...Handout: Problem Solving and 'C' Programming Version: PSC/Handout/1107/1.0 Date: 16-11-07 Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com Problem Solving and C Programming TABLE OF CONTENTS About this Document ....................................................................................................................6 Target Audience ...........................................................................................................................6 Objectives .....................................................................................................................................6 Pre-requisite .................................................................................................................................6 Session 2: Introduction to Problem Solving and Programming Languages ...........................7 Learning Objectives ......................................................................................................................7 Problem Solving Aspect ...............................................................................................................7 Program Development Steps .......................................................................................................8 Introduction to Programming Languages ...................................................................................14 Types and Categories of Programming......

Words: 4320 - Pages: 18

Premium Essay

Lg C Program

... About The Tutorial C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. C is the most widely used computer language. It keeps fluctuating at number one scale of popularity along with Java programming language, which is also equally popular and most widely used among modern software programmers. Audience This tutorial is designed for software programmers with a need to understand the C programming language starting from scratch. This tutorial will give you enough understanding on C programming language from where you can take yourself to higher level of expertise. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of Computer Programming terminologies. A basic understanding of any of the programming languages will help you in understanding the C programming concepts and move fast on the learning track. Copyright & Disclaimer  Copyright 2014 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however,......

Words: 13419 - Pages: 54

Free Essay

C Primer

...Third Edition March 26, 1998 ISBN: 0201824701, 1264 pages C++ Primer Third Edition Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and AddisonWesley was aware of a trademark claim, the designations have been printed in initial capital letters or all capital letters. The authors and publisher have taken care in preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The programs and applications presented in this book have been included for their instructional value. They have been tested with care, but are not guaranteed for any particular purpose. The authors and publisher do not offer any warranties or representations, nor do they accept any liabilities with respect to the programs or applications. The publisher offers discounts on this book when ordered in quantity for special sales. For more information please contact: Corporate, Government, and Special Sales Addison Wesley Longman, Inc. One Jacob Way R Copyright Information Copyright © 1998 by AT&T, Objectwrite, Inc., and José Lajoie e Library of Congress Cataloging-in-Publication Data Lippman, Stanley B. C++ Primer / Stanley B. Lippman, José Lajoie. — 3rd ed. e p.......

Words: 275162 - Pages: 1101

Free Essay

Arrays Versus Pointers

...Arrays versus Pointers A pointer is a variable which keeps a memory address. This address is the position of another item in memory. A pointer has variable name exactly like any other variable and also has got type which designates what type of variable its elements refer to. For instance, in case one variable has the memory address of another variable, the 1st variable is said to point to the second variable. Declaring a Pointer Pointers may be announced as we do normal variables, except for the pointer name has an asterisk before it to show that it's variable which is a pointer. The normal syntax for announcing a pointer is type* variable_name; We can put the asterisk near to variable name, but it’s a good programming routine to put the asterisk close type because it shows that the pointer variable points to that kind of variable. For instance, we wish to announce a pointer that keeps the memory address of an integer variable. The announcement would appear as follows int* ptr; There are 2 operators linked with pointers. 1. Address-of operator(&) This operator is utilized to get the address of a variable. It's a unary operator. Let's see an illustration on the way to utilize this operator. int var = 9; //declare a variable of integer type int* ptr; //declare pointer ptr = &var; //assign the address of var to pointer variable 2. Indirection operator(*) ...

Words: 288 - Pages: 2