music |
OSdata.com |
pointers
summary
This subchapter looks at pointers.
The educational goal of this subchapter is for the student to learn what pointers are and how to use them.
free computer programming text book projecttable of contents
|
music |
OSdata.com |
This subchapter looks at pointers.
The educational goal of this subchapter is for the student to learn what pointers are and how to use them.
free computer programming text book projecttable of contents
|
This subchapter is a stub section. It will be filled in with instructional material later. For now it serves the purpose of a place holder for the order of instruction.
Professors are invited to give feedback on both the proposed contents and the propsed order of this text book. Send commentary to Milo, PO Box 1361, Tustin, California, 92781, USA.
This subchapter looks at pointers.
Pointers also require sensible notation. np is just as mnemonic as nodepointer if you consistently use a naming convention from which np means node pointer is easily derived. Rob Pike, Notes on Programming in C, February 21, 1989
Of course Java has pointers. In fact, just about everything in Java is implicitly a pointer. They just call them references. There are advantages to having pointers implicit as well as disadvantages. Separately,there are advantages to having true local objects (as in C++) as well as disadvantages. Bjarne Stroustrup, Masterminds of Progtramming, Chapter One, 2009
What Java doesnt haveand good for Java for thatis C and C++sability to misuse pointers through pointer arithmetic. Well-written C++ doesnt suffer from that problem either: people use higher-level abstractions, such as iostreams, containers, and algorithms, rather than fiddling with pointers. Essentially all arrays and most pointers belong deep in implementations that most programmers dont have to see. Unfortunately, there is also lots of poorly written and unnecessarily low-level C++ around. Bjarne Stroustrup, Masterminds of Progtramming, Chapter One, 2009
The following material is from the unclassified Computer Programming Manual for the JOVIAL (J73) Language, RADC-TR-81-143, Final Technical Report of June 1981.
Chapter 1 INTRODUCTION, page 3
ITEM HEAD P DATA; A pointer item, whose value is the
address of a data object of type DATA.
Chapter 1 INTRODUCTION, page 5
1.1.5 Built-In Functions
The JOVIAL built-in functions provide advanced, specialized
operations that are not covered by the JOVIAL operators.
LOC(x) A pointer to the object referenced by r
NEXT(p,i) A pointer to the i'th data object after
the one selected by p
Chapter 1 Introduction, page 9
Stanford CS Education Library This [the following section until marked as end of Stanford University items] is document #101, Essential C, in the Stanford CS Education Library. This and other educational materials are available for free at http://cslibrary.stanford.edu/. This article is free to be used, reproduced, excerpted, retransmitted, or sold so long as this notice is clearly reproduced at its beginning. Copyright 1996-2003, Nick Parlante, nick.parlante@cs.stanford.edu.
A pointer is a value which represents a reference to another value sometimes known as the pointers pointee. Hopefully you have learned about pointers somewhere else, since the preceding sentence is probably inadequate explanation. This discussion will concentrate on the syntax of pointers in C -- for a much more complete discussion of pointers and their use see http://cslibrary.stanford.edu/102/, Pointers and Memory.
Syntactically C uses the asterisk or star (*) to indicate a pointer. C defines pointer types based on the type pointee. A char* is type of pointer which refers to a single char. A struct fraction* is type of pointer which refers to a struct fraction.
int* intPtr; // declare an integer pointer variable intPtr
char* charPtr; // declares a character pointer --
// a very common type of pointer
// Declare two struct fraction pointers
// (when declaring multiple variables on one line, the *
// should go on the right with the variable)
struct fraction *f1, *f2;The Floating *
In the syntax, the star is allowed to be anywhere between the base type and the variable name. Programmers have their own conventions-- I generally stick the * on the left with the type. So the above declaration of intPtr could be written equivalently
int *intPtr; // these are all the same
int * intPtr;
int* intPtr;Pointer Dereferencing
Well see shortly how a pointer is set to point to something -- for now just assume the pointer points to memory of the appropriate type. In an expression, the unary * to the left of a pointer dereferences it to retrieve the value it points to. The following drawing shows the types involved with a single pointer pointing to a struct fraction.
struct fraction* f1;
Expression Type f1 struct fraction* *f1 struct fraction (*f1).numerator int Theres an alternate, more readable syntax available for dereferencing a pointer to a struct. A -> at the right of the pointer can access any of the fields in the struct. So the reference to the numerator field could be written f1->numerator.
Here are some more complex declarations
struct fraction** fp; // a pointer to a pointer to a struct fraction
struct fraction fract_array[20]; // an array of 20 struct fractions
struct fraction* fract_ptr_array[20]; // an array of 20 pointers to
// struct fractionsOne nice thing about the C type syntax is that it avoids the circular definition problems which come up when a pointer structure needs to refer to itself. The following definition defines a node in a linked list. Note that no preparatory declaration of the node pointer type is necessary.
struct node {
int data;
struct node* next;
};The & Operator
The & operator is one of the ways that pointers are set to point to things. The & operator computes a pointer to the argument to its right. The argument can be any variable which takes up space in the stack or heap (known as an LValue technically). So &i and &(f1->numerator) are ok, but &6 is not. Use & when you have some memory, and you want a pointer to that memory.
void foo() {
int* p; // p is a pointer to an integer
int i;; // i is an integer
p = &i; // Set p to point to i
*p = 13; // Change what p points to -- in this case i -- to 13
// At this point i is 13. So is *p. In fact *p is i.
}When using a pointer to an object created with &, it is important to only use the pointer so long as the object exists. A local variable exists only as long as the function where it is declared is still executing (well see functions shortly). In the above example, i exists only as long as foo() is executing. Therefore any pointers which were initialized with &i are valid only as long as foo() is executing. This lifetime constraint of local memory is standard in many languages, and is something you need to take into account when using the & operator.
NULL
A pointer can be assigned the value 0 to explicitly represent that it does not currently have a pointee. Having a standard representation for no current pointee turns out to be very handy when using pointers. The constant NULL is defined to be 0 and is typically used when setting a pointer to NULL. Since it is just 0, a NULL pointer will behave like a boolean false when used in a boolean context. Dereferencing a NULL pointer is an error which, if you are lucky, the computer will detect at runtime -- whether the computer detects this depends on the operating system.
Pitfall -- Uninitialized Pointers
When using pointers, there are two entities to keep track of. The pointer and the memory it is pointing to, sometimes called the pointee. There are three things which must be done for a pointer/pointee relationship to work
(1) The pointer must be declared and allocated
(2) The pointee must be declared and allocated
(3) The pointer (1) must be initialized so that it points to the pointee (2)
The most common pointer related error of all time is the following: Declare and allocate the pointer (step 1). Forget step 2 and/or 3. Start using the pointer as if it has been setup to point to something. Code with this error frequently compiles fine, but the runtime results are disastrous. Unfortunately the pointer does not point anywhere good unless (2) and (3) are done, so the run time dereference operations on the pointer with * will misuse and trample memory leading to a random crash at some point.
{
int* p;
*p = 13; // NO NO NO p does not point to an int yet
asdf
// this just overwrites a random area in memory
}Of course your code wont be so trivial, but the bug has the same basic form: declare a pointer, but forget to set it up to point to a particular pointee.
Using Pointers
Declaring a pointer allocates space for the pointer itself, but it does not allocate space for the pointee. The pointer must be set to point to something before you can dereference it.
Heres some code which doesnt do anything useful, but which does demonstrate (1) (2) (3) for pointer use correctly
int* p; // (1) allocate the pointer
int i; // (2) allocate pointee
struct fraction f1; // (2) allocate pointee
p = &i; // (3) setup p to point to i
*p = 42; // ok to use p since it's setup
p = &(f1.numerator); // (3) setup p to point to a different int
*p = 22;
p = &(f1.denominator); // (3)
*p = 7;So far we have just used the & operator to create pointers to simple variables such as i. Later, well see other ways of getting pointers with arrays and other techniques.
See the discussion on C strings in the Stanford CS Education information in the subchapter on strings
Stanford CS Education Library This [the above section] is document #101, Essential C, in the Stanford CS Education Library. This and other educational materials are available for free at http://cslibrary.stanford.edu/. This article is free to be used, reproduced, excerpted, retransmitted, or sold so long as this notice is clearly reproduced at its beginning. Copyright 1996-2003, Nick Parlante, nick.parlante@cs.stanford.edu.
36 Access types allow the construction of linked data structures. A value of an access type represents a reference to an object declared as aliased or to an object created by the evaluation of an allocator. Several variables of an access type may designate the same object, and components of one object may designate the same or other objects. Both the elements in such linked data structures and their relation to other elements can be altered during program execution. Access types also permit references to subprograms to be stored, passed as parameters, and ultimately dereferenced as part of an indirect call. :Ada-Europes Ada Reference Manual: Introduction: Language Summary See legal information
Address registers store the addresses of specific memory locations. Often many integer and logic operations can be performed on address registers directly (to allow for computation of addresses).
Sometimes the contents of address register(s) are combined with other special purpose registers to compute the actual physical address. This allows for the hardware implementation of dynamic memory pages, virtual memory, and protected memory.
The number of bits of an address register (possibly combined with information from other registers) limits the maximum amount of addressable memory. A 16-bit address register can address 64K of physical memory. A 24-bit address register can address address 16 MB of physical memory. A 32-bit address register can address 4 GB of physical memory. A 64-bit address register can address 1.8446744 x 1019 of physical memory. Addresses are always unsigned binary numbers. See number of bits.
Index registers are used to provide more flexibility in addressing modes, allowing the programmer to create a memory address by combining the contents of an address register with the contents of an index register (with displacements, increments, decrements, and other options). In some processors, there are specific index registers (or just one index register) that can only be used only for that purpose. In some processors, any data register, address register, or general register (or some combination of the three) can be used as an index register.
Base registers or segment registers are used to segment memory. Effective addresses are computed by adding the contents of the base or segment register to the rest of the effective address computation. In some processors, any register can serve as a base register. In some processors, there are specific base or segment registers (one or more) that can only be used for that purpose. In some processors with multiple base or segment registers, each base or segment register is used for different kinds of memory accesses (such as a segment register for data accesses and a different segment register for program accesses).
See also Registers
Address movement instructions move addresses from one location to another. The source and destination locations are determined by the addressing modes, and can be registers or memory. Address movement instructions can come in a variety of sizes. Address movement instructions destroy the previous contents of the destination. Address movement instructions typically do not modify processor flags. When the destination is a register and the address is smaller than the full register size, the data might be placed only in the low order bits (leaving high order bits unchanged), or might be zero- or sign-extended to fill the entire register (some processors only use one choice, others permit the programmer to choose how this is handled).
See also Data Movement Instructions in Assembly Language
Coding example: I am making heavily documented and explained open source code for a method to play music for free almost any song, no subscription fees, no download costs, no advertisements, all completely legal. This is done by building a front-end to YouTube (which checks the copyright permissions for you).
View music player in action: www.musicinpublic.com/.
Create your own copy from the original source code/ (presented for learning programming).
return to table of contents
free downloadable college text book
Because I no longer have the computer and software to make PDFs, the book is available as an HTML file, which you can convert into a PDF.
previous page | next page |
Tweets by @osdata |
free computer programming text book projectBuilding a free downloadable text book on computer programming for university, college, community college, and high school classes in computer programming. If you like the idea of this project, Supporting the entire project: If you have a business or organization that can support the entire cost of this project, please contact Pr Ntr Kmt (my church) free downloadable college text book on computer programming. |
This web site handcrafted on Macintosh computers using Tom Benders Tex-Edit Plus and served using FreeBSD .
UNIX used as a generic term unless specifically used as a trademark (such as in the phrase UNIX certified). UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company Ltd.
Names and logos of various OSs are trademarks of their respective owners.
Copyright © 2010, 2011, 2012 Milo
Created: November 1, 2010
Last Updated: September 30, 2012
return to table of contents
free downloadable college text book
previous page | next page |