Free Essay

Tutorial on Pointers and Arrays in C

In:

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

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

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, the...

Words: 13419 - Pages: 54

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 Variables...

Words: 11246 - Pages: 45

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

Premium Essay

Java

...Programming Language Material drawn from [JDK99,Sun96,Mitchell99,Mancoridis00] Software Design (Java Tutorial) © SERG Java Features • “Write Once, Run Anywhere.” • Portability is possible because of Java virtual machine technology: – Interpreted – JIT Compilers • Similar to C++, but “cleaner”: – No pointers, typedef, preprocessor, structs, unions, multiple inheritance, goto, operator overloading, automatic coercions, free. Software Design (Java Tutorial) © SERG Java Subset for this Course • We will focus on a subset of the language that will allow us to develop a distributed application using CORBA. • Input and output will be character (terminal) based. • For detailed treatment of Java visit: – http://java.sun.com/docs/books/tutorial/index.html Software Design (Java Tutorial) © SERG Java Virtual Machine • Java programs run on a Java Virtual Machine. • Features: – – – – – Security Portability Superior dynamic resource management Resource location transparency Automatic garbage collection Software Design (Java Tutorial) © SERG The Java Environment Java Source File (*.java) Java Compiler (javac) Java Bytecode File (*.class) Java Virtual Machine (java) Software Design (Java Tutorial) © SERG Program Organization Source Files (.java) Running Application Running Applet JAVA BYTECODE COMPILER Class Files (.class) JAVA VIRTUAL MACHINE WEB BROWSER Software Design (Java Tutorial) © SERG Program Organization Standards • Each class is implemented in its own source file....

Words: 5230 - Pages: 21

Premium Essay

Computer Science

...2006 2. Data communication and networks- Forouzan-4TH Edition Reference Books: 3.Data Structures & Algorithms Using C- R.S Salaria-2nd Edition 4.Data Structures,Algorithms and applications in C++ --Sartaj Sahni—2nd Edition 5.PC Hardware in a Nutshell-Robert Bruce Thomsan and Barbara Fritchman Thomsan—July2003 :Second Edition Other readings: |Sr.No. |Journal articles as compulsory readings (Complete reference) | |6. |Cisco system advanced exam guide-CISCO press | |7. |Cisco system CCNA Exam dump guide –CISCO press | Relevant websites: |S.No. |Web address |Salient Features | |8. |http://www.java2s.com/Tutorial/C/0260__Data-Structure |A web page on Data Structure| | | |in C | |9. |http://www.java2s.com/Code/C/Data-Structure-Algorithm/CatalogData-Structure-Algorithm.htm |A web page on | | | ...

Words: 1499 - Pages: 6

Premium Essay

Learn C Programming Language in 24 Hours

...Yourself C in 24 Hours Previous | Table of Contents | Next Hour 1 - Getting Started A journey of a thousand miles is started by taking the first step. —Chinese proverb High thoughts must have high language. —Aristophanes Welcome to Teach Yourself C in 24 Hours. In this first lesson you'll learn the following:     What C is Why you need to learn C The ANSI standard Hardware and software required in order to run the C program What Is C? C is a programming language. The C language was first developed in 1972 by Dennis Ritchie at AT&T Bell Labs. Ritchie called his newly developed language C simply because there was a B programming language already. (As a matter of fact, the B language led to the development of C.) C is a high-level programming language. In fact, C is one of the most popular general-purpose programming languages. In the computer world, the further a programming language is from the computer architecture, the higher the language's level. You can imagine that the lowest-level languages are machine languages that computers understand directly. The high-level programming languages, on the other hand, are closer to our human languages. (See Figure 1.1.) Figure 1.1. The language spectrum. High-level programming languages, including C, have the following advantages:    Readability: Programs are easy to read. Maintainability: Programs are easy to maintain. Portability: Programs are easy to port across different computer platforms. The C language's...

Words: 73255 - Pages: 294

Premium Essay

Comp Intro

...account. Otherwise, your email may be accidentally filtered/deleted. If I don’t respond in two days, please re-send the email or talk to me directly after class or during my office hours. Course Description This course is an introduction to structured computer programming. Students will study algorithms and top-down design, and will implement algorithms in a procedural programming language. Please refer to http://www.ufv.ca/calendar/CourseOutlines/PDFs/COMP/COMP150-20100423.pdf for further information. NOTE: COMP 150 or 152 (respectively) cannot be taken for further credit. Prerequisite B.C. Principles of Math 11 with a grade of C or better or MATH 085 with a C or better. Competent in computer skills. Course Text & Material Reference: Schaums’ Outline: Programming with C++ John Hubbard McGraw-Hill ISBN: 0-07-135346-1 Text: C++ for Everyone Cay Horstmann Wiley ISBN-13: 978-0-470-92713-7 Note: You may need a flash drive if you want to keep your own copy and transfer files. Other Course Resources Q:\cis\Jon Quah\comp150 It is your responsibility to check the website often as files may be added or updated at any time. Course Objectives/Outcomes On completion of this course, the student will be able to: * design a structured solution to a problem by repeatedly breaking the problem into a sequence of simpler sub problems, * implement a structured design as a computer program, with separate functions corresponding to the sub problems of...

Words: 832 - Pages: 4

Free Essay

Proposal

...8086 assembler tutorial for beginners (part 2) Memory Access to access memory we can use these four registers: BX, SI, DI, BP. combining these registers inside [ ] symbols, we can get different memory locations. these combinations are supported (addressing modes): [BX + SI] [BX + DI] [BP + SI] [BP + DI] | [SI] [DI] d16 (variable offset only) [BX] | [BX + SI + d8] [BX + DI + d8] [BP + SI + d8] [BP + DI + d8] | [SI + d8] [DI + d8] [BP + d8] [BX + d8] | [BX + SI + d16] [BX + DI + d16] [BP + SI + d16] [BP + DI + d16] | [SI + d16] [DI + d16] [BP + d16] [BX + d16] | d8 - stays for 8 bit signed immediate displacement (for example: 22, 55h, -1, etc...) d16 - stays for 16 bit signed immediate displacement (for example: 300, 5517h, -259, etc...). displacement can be a immediate value or offset of a variable, or even both. if there are several values, assembler evaluates all values and calculates a single immediate value.. displacement can be inside or outside of the [ ] symbols, assembler generates the same machine code for both ways. displacement is a signed value, so it can be both positive or negative. generally the compiler takes care about difference between d8 and d16, and generates the required machine code. for example, let's assume that DS = 100, BX = 30, SI = 70. The following addressing mode: [BX + SI] + 25 is calculated by processor to this physical address: 100 * 16 + 30 + 70 + 25 = 1725. by default DS segment register is used for all modes except those...

Words: 2749 - Pages: 11

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 vuln´rabilit´s...

Words: 22394 - Pages: 90

Free Essay

Ali94

...Programs and Designs Scott Meyers More Effective C ADDISON-WESLEY PROFESSIONAL COMPUTING SERIES ++ Conforms to the new ISO/ANSI C++ standard! From the Library of Yuri Khan Praise for More Effective C++: 35 New Ways to Improve Your Programs and Designs “This is an enlightening book on many aspects of C++: both the regions of the language you seldom visit, and the familiar ones you THOUGHT you understood. Only by understanding deeply how the C++ compiler interprets your code can you hope to write robust software using this language. This book is an invaluable resource for gaining that level of understanding. After reading this book, I feel like I've been through a code review with a master C++ programmer, and picked up many of his most valuable insights.” — Fred Wild, Vice President of Technology, Advantage Software Technologies “This book includes a great collection of important techniques for writing programs that use C++ well. It explains how to design and implement the ideas, and what hidden pitfalls lurk in some obvious alternative designs. It also includes clear explanations of features recently added to C++. Anyone who wants to use these new features will want a copy of this book close at hand for ready reference.” — Christopher J. Van Wyk, Professor, Mathematics and Computer Science, Drew University “Industrial strength C++ at its best. The perfect companion to those who have read Effective C++.” — Eric Nagler, C++ Instructor and Author, University of California...

Words: 43056 - Pages: 173

Free Essay

Concepts of Programming Language Solutions

...tenth edition evolved from the ninth through several different kinds of changes. To maintain the currency of the material, some of the discussion of older programming languages has been removed. For example, the description of COBOL’s record operations was removed from Chapter 6 and that of Fortran’s Do statement was removed from Chapter 8. Likewise, the description of Ada’s generic subprograms was removed from Chapter 9 and the discussion of Ada’s asynchronous message passing was removed from Chapter 13. On the other hand, a section on closures, a section on calling subprograms indirectly, and a section on generic functions in F# were added to Chapter 9; sections on Objective-C were added to Chapters 11 and 12; a section on concurrency in functional programming languages was added to Chapter 13; a section on C# event handling was added to Chapter 14;. a section on F# and a section on support for functional programming in primarily imperative languages were added to Chapter 15. In some cases, material has been moved....

Words: 7025 - Pages: 29

Free Essay

Reverse Engineering

...About the Tutorial Assembly language is a low-level programming language for a computer or other programmable device specific to a particular computer architecture in contrast to most high-level programming languages, which are generally portable across multiple systems. Assembly language is converted into executable machine code by a utility program referred to as an assembler like NASM, MASM, etc. Audience This tutorial has been designed for those who want to learn the basics of assembly programming from scratch. This tutorial will give you enough understanding on assembly programming from where you can take yourself to higher levels 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 Assembly 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, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt...

Words: 16458 - Pages: 66

Premium Essay

Computers

...C Primer Plus Sixth Edition Developer’s Library ESSENTIAL REFERENCES FOR PROGRAMMING PROFESSIONALS Developer’s Library books are designed to provide practicing programmers with unique, high-quality references and tutorials on the programming languages and technologies they use in their daily work. All books in the Developer’s Library are written by expert technology practitioners who are especially skilled at organizing and presenting information in a way that’s useful for other programmers. Key titles include some of the best, most widely acclaimed books within their topic areas: PHP & MySQL Web Development Luke Welling & Laura Thomson ISBN 978-0-672-32916-6 Python Essential Reference David Beazley ISBN-13: 978-0-672-32978-4 MySQL Paul DuBois ISBN-13: 978-0-321-83387-7 PostgreSQL Korry Douglas ISBN-13: 978-0-672-32756-8 Linux Kernel Development Robert Love ISBN-13: 978-0-672-32946-3 C++ Primer Plus Stephen Prata ISBN-13: 978-0-321-77640-2 Developer’s Library books are available in print and in electronic formats at most retail and online bookstores, as well as by subscription from Safari Books Online at safari. informit.com Developer’s Library informit.com/devlibrary C Primer Plus Sixth Edition Stephen Prata Upper Saddle River, NJ • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Cape Town • Sydney • Tokyo • Singapore • Mexico City C Primer Plus Sixth...

Words: 125302 - Pages: 502

Free Essay

Student

...CONCEPTS OF PROGRAMMING LANGUAGES TENTH EDITION This page intentionally left blank CONCEPTS OF PROGRAMMING LANGUAGES TENTH EDITION R OB E RT W. S EB ES TA University of Colorado at Colorado Springs Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo Vice President and Editorial Director, ECS: Marcia Horton Editor in Chief: Michael Hirsch Executive Editor: Matt Goldstein Editorial Assistant: Chelsea Kharakozova Vice President Marketing: Patrice Jones Marketing Manager: Yez Alayan Marketing Coordinator: Kathryn Ferranti Marketing Assistant: Emma Snider Vice President and Director of Production: Vince O’Brien Managing Editor: Jeff Holcomb Senior Production Project Manager: Marilyn Lloyd Manufacturing Manager: Nick Sklitsis Operations Specialist: Lisa McDowell Cover Designer: Anthony Gemmellaro Text Designer: Gillian Hall Cover Image: Mountain near Pisac, Peru; Photo by author Media Editor: Dan Sandin Full-Service Vendor: Laserwords Project Management: Gillian Hall Printer/Binder: Courier Westford Cover Printer: Lehigh-Phoenix Color This book was composed in InDesign. Basal font is Janson Text. Display font is ITC Franklin Gothic. Copyright © 2012, 2010, 2008, 2006, 2004 by Pearson Education, Inc., publishing as Addison-Wesley. All rights reserved. Manufactured...

Words: 142312 - Pages: 570