FACTOID # 25: If you're in Montserrat, watch your back! Nearly 1% of the population are police officers.
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > Pointer (computing)

In computer science, a pointer is a programming language data type whose value refers directly to (or “points to”) another value stored elsewhere in the computer memory using its address. Obtaining the value to which a pointer refers is called dereferencing the pointer. A pointer is a simple implementation of the general reference data type (although it is quite different from the facility referred to as a reference in C++). Computer science, or computing science, is the study of the theoretical foundations of information and computation and their implementation and application in computer systems. ... A programming language is an artificial language that can be used to control the behavior of a machine, particularly a computer. ... A data type is a constraint placed upon the interpretation of data in a type system in computer programming. ... The terms storage (U.K.) or memory (U.S.) refer to the parts of a digital computer that retain physical state (data) for some interval of time, possibly even after electrical power to the computer is turned off. ... In computer science, a memory address is a unique identifier for a memory location at which a CPU or other device can store a piece of data for later retrieval. ... This article discusses a general notion of reference in computing. ... In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C, which is a reference in the general sense but not in the sense used by C++. // Syntax and terminology The declaration of the form <Type...


Pointers are so commonly used as references that sometimes people use the word “pointer” to refer to references in general; however, more properly it only applies to data structures whose interface explicitly allows it to be manipulated as a memory address. If you are seeking general information on a small piece of data used to find an object, see reference (computer science). This article discusses a general notion of reference in computing. ...

Contents

Architectural roots

Pointers are a very thin abstraction on top of the addressing capabilities provided by most modern architectures. In the simplest scheme, an address, or a numeric index, is assigned to each unit of memory in the system, where the unit is typically either a byte or a word, effectively transforming all of memory into a very large array. Then, if we have an address, the system provides an operation to retrieve the value stored in the memory unit at that address. In computer science, abstraction is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time. ... The software architecture of a program or computing system is the structure or structures of the system, which comprise software elements, the externally visible properties of those elements, and the relationships between them. ... In computer science, a memory address is a unique identifier for a memory location at which a CPU or other device can store a piece of data for later retrieval. ... Index has two distinct meanings in computer science: an integer which identifies an array element, and a data structure which enables sublinear-time lookup. ... In computer science a byte is a unit of measurement of information storage, often containing eight bits. ... In computing, word is a term for the natural unit of data used by a particular computer design. ... This article or section does not cite its references or sources. ...


In the usual case, a pointer is large enough to hold more different addresses than there are units of memory in the system. This introduces the possibility that a program may attempt to access an address which corresponds to no unit of memory. This is one example of what is called a segmentation fault (segfault). On the other hand, some systems have more units of memory than there are addresses. In this case, a more complex scheme such as memory segmentation or paging is employed to use different parts of the memory at different times. It has been suggested that Access violation be merged into this article or section. ... Segmentation is one of the most common ways to achieve memory protection; another common one is paging. ... In computer operating systems, paging memory allocation, paging refers to the process of managing program access to virtual memory pages that do not currently reside in RAM. It is implemented as a task that resides in the kernel of the operating system and gains control when a page fault takes...


In order to provide a consistent interface, some architectures provide memory-mapped I/O, which allows some addresses to refer to units of memory while others refer to device registers of other devices in the computer. There are analogous concepts such as file offsets, array indicies, and remote object references that serve some of the same purposes as addresses for other types of objects. Memory-mapped I/O (MMIO) and port I/O (also called port-mapped I/O or PMIO) are two complementary methods of performing input/output between the CPU and I/O devices in a computer. ... A Device Register is the view any device presents to a programmer. ... This article or section does not cite its references or sources. ...


Uses

Pointers are directly supported without restrictions in C, C++, Pascal and most assembly languages. They are primarily used for constructing references, which in turn are fundamental to constructing nearly all data structures, as well as in passing data between different parts of a program. C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ... C++ (pronounced see plus plus, IPA: ) is a general-purpose, high-level programming language with low-level facilities. ... Pascal is an imperative computer programming language, developed in 1970 by Niklaus Wirth as a language particularly suitable for structured programming. ... An assembly language is a low-level language used in the writing of computer programs. ... This article discusses a general notion of reference in computing. ... A binary tree, a simple type of branching linked data structure. ...


In functional programming languages that rely heavily on lists, pointers and references are managed abstractly by the language using internal constructs like cons. CONS, Connection-Oriented Network Service, is one of the two OSI stack network layer protocols, the other being CLNS (Connectionless Network Service). ...


When dealing with arrays, the critical lookup operation typically involves a stage called address calculation which involves constructing a pointer to the desired data element in the array. In other data structures, such as linked lists, pointers are used as references to explicitly tie one piece of the structure to another. This article or section does not cite its references or sources. ...


Pointers are used to pass parameters by reference. This is useful if we want a function's modifications to a parameter to be visible to the function's caller. This is also useful for returning multiple values from a function.


C pointers

The basic syntax to define a pointer is

 int *money; 

This declares money as a pointer to an integer. Since the contents of memory are not guaranteed to be of any specific value in C, care must be taken to ensure that the address that money points to is valid. This is why it is suggested to initialize the pointer to NULL

 int *money = NULL; 

If a NULL pointer is dereferenced then a runtime error will occur and execution will stop likely with a segmentation fault.


Once a pointer has been declared then, perhaps, the next logical step is to point it at something

 int a = 5; int *money = NULL; money = &a; 

This assigns the value of money to be the address of a. For example, if a is stored at memory location of 0x8130 then the value of money will be 0x8130 after the assignment. To dereference the pointer, an asterisk is used again

 *money = 8; 

This says to take the contents of money (which is 0x8130), go to that address in memory and set its value to 8. If a were then accessed then its value will be 20.


This example may be more clear if memory were examined directly. Assume that a is located at address 0x8130 in memory and money at 0x8134; also assume this is a 32-bit machine such that an int is 32-bits wide. The following is what would be in memory after the following code snippet were executed

 int a = 5; int *money = NULL; 
Address Contents
0x8130 0x00000005
0x8134 0x00000000

(The NULL pointer shown here is 0x00000000.) By assigning the address of a to money

 money = &a; 

yields the following memory values

Address Contents
0x8130 0x00000005
0x8134 0x00008130

Then by dereferencing money by doing

 *money = 8; 

the computer will take the contents of money (which is 0x8130), go to that address, and assign 8 to that location yielding the following memory.

Address Contents
0x8130 0x00000008
0x8134 0x00008130

Clearly, accessing a will yield the value of 8 because the previous instruction modified the contents of a by way of the pointer money.


C arrays

Taking C pointers to the next step is the array.


C has no native data type of an array (in the sense like PHP and python have an array and list, respectively). Arrays in C are just pointers to consecutive areas of memory. For example, an array array can be declared in the following manner

 int array[5]; 

This allocates a block of five integers and declares array as a pointer to this block. Default values can be declared like

 int array[5] = {2,4,3,1,5}; 

If you assume that array is located in memory at address 0x8130 and the five integers are placed in memory starting at 0x1000 and on a 32-bit little-endian machine then memory will contain the following: When integers or any other data are represented with multiple bytes, there is no unique way of ordering of those bytes in memory or in a transmission over some medium, and so the order is subject to arbitrary convention. ...

0 1 2 3
1000 02 00 00 00
1004 04 00 00 00
1008 03 00 00 00
100C 01 00 00 00
1010 05 00 00 00
...
8130 00 10 00 00

Representing here are five integers: 2, 4, 3, 1, and 5. These five integers occupy 32 bits (4 bytes) each with the least-significant byte stored first (this is a little-endian architecture) and are stored consecutively started at address 0x1000.


The essence to this example is that variable array is stored in memory at address 0x8130. The contents at this address is 0x1000. When the contents of array are used as a pointer then the value in array means a memory location. The syntax for C with pointers is exacting:

  • array means 0x1000
  • array+1 means 0x1004 (note that the "+1" really means to add one times the size of array (4 bytes) not literally "plus one")
  • &array means 0x8130
  • *array means to dereference the contents of array which means to consider the contents as a memory address (0x1000) and to go look up the value at that memory location (0x0001)
  • array[i] means the ith index of array which is translated into *(array + i)

The last example is how to access the contents of array. Breaking it down:

  • array + i is the memory location of the ith element of array
  • *(array + i) takes that memory address and dereferences it to access the value.

So:

  • array means 0x1000
  • array+0 means 0x1000
  • array+1 means 0x1004
  • array+2 means 0x1008
  • array+3 means 0x100C
  • array+4 means 0x1010
  • array[0] means *(array + 0) which is the value 0x0002
  • array[1] means *(array + 1) which is the value 0x0004
  • array[2] means *(array + 2) which is the value 0x0003
  • array[3] means *(array + 3) which is the value 0x0001
  • array[4] means *(array + 4) which is the value 0x0005

array+i is called pointer arithmetic because it performs arithmetic operations on a pointer.


C linked list

Below is an example of the definition of a linked list in C; this is not possible in C without pointers. In computer science, a linked list is one of the fundamental data structures used in computer programming. ...

 /* the empty linked list is * represented by NULL or some * other signal value */ #define EMPTY_LIST NULL struct link { /* the data of this link */ void *data; /* the next link; EMPTY_LIST if this is the last link */ struct link *next; }; 

Note that this pointer-recursive definition is essentially the same as the reference-recursive definition from the Haskell programming language: Haskell is a standardized pure functional programming language with non-strict semantics, named after the logician Haskell Curry. ...

 data Link a = Nil | Cons a (Link a) 

Nil is the empty list, and Cons a (Link a) is a cons cell of type a with another link also of type a. CONS, Connection-Oriented Network Service, is one of the two OSI stack network layer protocols, the other being CLNS (Connectionless Network Service). ...


The definition with references, however, is type-checked and doesn't use potentially confusing signal values. For this reason, data structures in C are usually dealt with via wrapper functions, which are carefully checked for correctness.


Pass by references

Pointers can be used to pass variables by reference, allowing their value to be changed. For example:

 #include <stdio.h> void alter(int *n) { *n = 120; } int main() { int x = 24; /* the '&' operator (read "reference") retrieves * the address of a variable */ int *address = &x; 
 /* show x */ printf("%dn", x); /* show x's address */ printf("%pn", (void *)address); /* pass x's address to alter, x is passed "by reference" */ alter(&x); /* show x's new value */ printf("%dn", x); /* notice that x's address is not altered */ printf("%p %pn", (void *)address, (void *)&x); return 0; } 

Lastly, on some computing architectures, pointers can be used to directly manipulate memory or memory mapped devices. In the mid 80's, using the BIOS to access the video capabilities of PCs was slow. Applications that were display-intensive typically used to access CGA video memory directly by casting the hexadecimal constant 0xB8000000 to a pointer to an array of 80 unsigned 16-bit int values. Each value consisted of an ASCII code in the low byte, and a colour in the high byte. Thus, to put the letter 'A' at row 5, column 2 in bright white on blue, one would write code like the following: This article or section does not adequately cite its references or sources. ... The Color Graphics Adapter (CGA), introduced in 1981, was IBMs first color graphics card, and the first color computer display standard for the IBM PC. The standard IBM CGA graphics card was equipped with 16 kilobytes of video memory. ... In mathematics and computer science, hexadecimal, base-16, or simply hex, is a numeral system with a radix, or base, of 16, usually written using the symbols 0–9 and A–F, or a–f. ... There are 95 printable ASCII characters, numbered 32 to 126. ...

 #define VID ((unsigned (*)[80])0xB8000000) void foo() { VID[4][1] = 0x1F00 | 'A'; } 

Typed pointers and casting

In many languages, pointers have the additional restriction that the object they point to has a specific type. For example, a pointer may be declared to point to an integer; the language will then attempt to prevent the programmer from pointing it to objects which are not integers, such as floating-point numbers, eliminating some errors. In computer science, a datatype or data type (often simply a type) is a name or label for a set of values and some operations which one can perform on that set of values. ... The integers are commonly denoted by the above symbol. ... A floating-point number is a digital representation for a number in a certain subset of the rational numbers, and is often used to approximate an arbitrary real number on a computer. ...


For example, in C

 int *money; char *bags; 

money would be an integer pointer and bags would be a char pointer. The following would yield a compiler warning of "assignment from incompatible pointer type" under GCC GCC may stand for: Gulf Cooperation Council GNU Compiler Collection (formerly, the GNU C Compiler) Garde côtière canadienne (Canadian Coast Guard) Germanna Community College Glendale Community College global carbon cycle Global Climate Coalition Grand Council of the Crees (gcc. ...

 bags = money; 

because money and bags were declared with different types. To appease the compiler, it must be made explicit that you do indeed wish to make the assignment through the use of casting it

 bags = (char *)money; 

which says to cast the integer pointer of money to a char pointer and assign to bags.


In languages that allow pointer arithmetic, arithmetic on pointers take into account the size of the type. For example, adding an integer to a pointer produces another pointer that points to an address that is higher by that number times the size of the type. This allows us to easily compute the address of elements of an array of a given type. This was shown in the example above with C arrays.


However, few languages strictly enforce pointer types, because programmers often run into situations where they want to treat an object of one type as though it were of another type. For these cases, it is possible to typecast, or cast, the pointer. Some casts are always safe, while other casts are dangerous, possibly resulting in incorrect behavior. Although it's impossible in general to determine at compile-time which of these casts are safe, some languages store run-time type information which can be used to confirm that these dangerous casts are valid at runtime. Other languages merely accept a conservative approximation of safe casts, or none at all. This article should be merged with type_conversion. ... In programming, Runtime Type Information (RTTI, RunTime Type Identification) means keeping information about an objects datatype in memory at runtime. ...


Making pointers safer

Because pointers allow a program to access objects that are not explicitly declared beforehand, they enable a variety of programming errors. However, the power they provide is so great that it can be difficult to do some programming tasks without them. To help deal with their problems, many languages have created objects that have some of the useful features of pointers, while avoiding some of their pitfalls. The word error has different meanings in different domains. ... Anti-patterns, also referred to as pitfalls, are classes of commonly-reinvented bad solutions to problems. ...


One major problem with pointers is that, as long as they can be directly manipulated as a number, they can be made to point to unused addresses or to data which is being used for other purposes. Many languages, including most functional programming languages and recent imperative languages like Java, replace pointers with a more opaque type of reference, typically referred to as simply a reference, which can only be used to refer to objects and not manipulated as numbers, preventing this type of error. Array indexing is handled as a special case. Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions. ... Java is an object-oriented applications programming language developed by Sun Microsystems in the early 1990s. ...


A pointer which does not have any address assigned to it is called a wild pointer. Any attempt to use such uninitialized pointers can cause unexpected behaviour, either because the initial value is not a valid address, or because using it may damage the runtime system and other unrelated parts of the program.


In systems with explicit memory allocation, it's possible to create a dangling pointer by deallocating the memory region it points into. This type of pointer is dangerous and subtle, because a deallocated memory region may contain the same data as it did before it was deallocated, but may be then reallocated and overwritten by unrelated code, unbeknownst to the earlier code. Languages with garbage collection prevent this type of error. Dangling pointers in programming are pointers whose objects have since been deleted or deallocated, without modifying the value of the pointer. ... In computer science, garbage collection (also known as GC) is a form of automatic memory management. ...


Some languages, like C++, support smart pointers, which use a simple form of reference counting to help track allocation of dynamic memory in addition to acting as a reference. In the absence of reference cycles, where an object refers to itself indirectly through a sequence of smart pointers, these eliminate the possibility of dangling pointers and memory leaks. A smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking. ... In computer science, reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object or block of memory. ...


The null pointer

A null pointer has a reserved value, often but not necessarily the value zero, indicating that it refers to no object. Null pointers are used routinely, particularly in C and C++ where the compile time constant NULL is used, to represent exceptional conditions such as the lack of a successor to the last element of a linked list, while maintaining a consistent structure for the list nodes. This use of null pointers can be compared to the use of null values in relational databases and to the “Nothing” value in the “Maybe” monad. In C, each pointer type has its own null value, and sometimes they have different representations. In computer programming, null is a special value for a pointer (or other kind of reference) used to signify that the pointer intentionally does not have a target. ... In computer science, a linked list is one of the fundamental data structures used in computer programming. ... A relational database is a database that conforms to the relational model, and refers to a databases data and schema (the databases structure of how that data is arranged). ... Some functional programming languages make use of monads[1] [2] to structure programs which include operations that must be executed in a specific order. ...


Because it refers to nothing, an attempt to dereference a null pointer can cause a run-time error that usually terminates the program immediately (in the case of C, often with a segmentation fault, since the address literally corresponding to the null pointer will likely not be allocated to the running program). In Java, access to a null reference triggers a NullPointerException, which can be caught (but a common practice is to attempt to ensure such exceptions never occur). In safe languages a possibly null pointer can be replaced with a tagged union which enforces explicit handling of the exceptional case; in fact, a possibly-null pointer can be seen as a tagged union with a computed tag. In computer science, a tagged union, also called a variant, variant record, discriminated union, or disjoint union, is a data structure used to hold a value that could take on several different, but fixed types. ...


A null pointer should not be confused with an uninitialized pointer: a null pointer is guaranteed to compare unequal to a pointer to any object or function, whereas an uninitialized pointer might have any value. Two separate null pointers are guaranteed to compare equal and ANSI C guarantees that any NULL pointer will be equal to 0 in a comparison. ANSI C (Standard C) is a variant of the C programming language. ...


malloc returns a NULL pointer if it is unable to allocate the memory region requested; this is a way of signalling to the caller that there is insufficient memory available. Some implementations of malloc allow malloc(0) to return a NULL pointer as a successful allocation and will both return NULL and set errno if the malloc failed. In computing, malloc is a subroutine provided in the C programming languages and C++ programming languages standard library for performing dynamic memory allocation. ... In computer programming, error codes are enumerated messages that correspond to faults in a specific software application. ...


Wild pointers

Wild pointers are pointers that have not been initialized (that is, set to point to a valid address) and may make a program crash or behave oddly. In the Pascal or C programming languages, pointers that are not specifically initialized may point to unpredictable addresses in memory. Pascal is an imperative computer programming language, developed in 1970 by Niklaus Wirth as a language particularly suitable for structured programming. ... C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ...


The following example code shows a wild pointer:

 #include <stdio.h> #include <stdlib.h> int main(void) { /* (undefined) value of some place on the heap */ char *p1 = malloc(); /* wild (uninitialized) pointer */ char *p2; /* undefined value, may not be a valid address */ printf("Address of p2: %pn", (void *)p2); /* random value at random address. * if you are LUCKY, this will cause an addressing exception */ printf("Value of *p2: %cn", *p2); return 0; } 

The problems with invalid pointers include more than simply uninitialized values.


For instance, pointers can be used after the object or variable they point to no longer exists, or has gone out of scope, as in the example below. If such an invalid pointer is used, the program will probably not immediately crash, but the result will still probably be incorrect, and the failure will probably be hard to track down.

 #include <stdio.h> #include <stdlib.h> /* p is a pointer to a pointer to an int */ int badIdea(int **p) { /* allocate an int on the stack */ int x = 1; /* assign value of x to int that pointer p points to */ **p = x; /* make the pointer that p points to point to x */ *p = &x; /* after return x is out of scope and undefined */ return x; } int main(void) { int y = 0; /* initialize pointer to y */ int *p1 = &y; /* a good habit to form */ int *p2 = NULL; /* prints address of y */ printf("Address of p1: %pn", p1); /* prints value of y */ printf("Value of *p1: %dn", *p1); /* changes y and changes p1 */ y = badIdea(&p1); /* p1 now points to where x was * The place where x was will get clobbered, * for instance, on the next interrupt, or on * the next subroutine call, as below.... */ /* some other code that also uses the stack */ p2 = malloc(5 * sizeof *p2); /* this probably will NOT crash, * but value printed is unpredictable */ /* prints value of where x was */ printf("Value of *p1: %pn", *p1); return 0; } 

A very common problem is using a pointer to the heap after that memory has been deallocated, as in this example. The invalid copies of the pointer are usually much harder to find than here.

 #include <stdio.h> #include <stdlib.h> int main(void) { /* initialize pointer to heap */ int *p1 = malloc(sizeof *p1); /* make a copy */ int *p2 = p1; /* initialize the heap */ *p1 = 0; /* points into the heap */ printf("Address of p2: %pn", (void *)p2); /* should print zero */ printf("Value of *p2: %dn", *p2); /* deallocate the memory */ free(p1); /* other code, possibly using the heap */ .... /* p2 still points to the original allocation, * but who knows what is there */ printf("Value of *p2: %dn", *p2); /* invalid use of p2 */ return 0; } 

A third way that pointers can be misused is to access outside the data structure they point to. Here is a simple example.

 #include <stdio.h> #include <stdlib.h> int main(void) { /* create a variable */ int y = 5; /* initialize pointer to y */ int *p1 = &y; /* address of y */ printf("Address of p1: %pn", (void *)p1); /* value of y */ printf("Value of *p1: %dn", *p1); /* allowed pointer arithmetic */ p1 = p1 + y; /* p1 no longer points to y */ printf("Value of *p1: %dn", *p1); return 0; } 

If a pointer is used to write beyond the end of a local buffer, the stack can be destroyed. In the case below, the problem will probably manifest when the main program returns because the x86 architecture stores a procedure's caller return address in the stack.

 #include <stdio.h> #include <stdlib.h> /* copy source to destination, no check on sizes */ void strcopy(char *d, char *s) { /* copy until '0' encountered */ while (*d++ = *s++) ; } int main(void) { /* create a local buffer */ char y[3]; /* another buffer on heap */ char *p1 = malloc(10 * sizeof *p1); /* terminate the larger buffer */ p1[9] = '0'; /* overflow the local buffer */ strcopy(y, p1); free(p1); return 0; /* now bad stuff happens */ } 

Double indirection

In C, it is possible to have a pointer point at another pointer. This can make manipulating certain data structures particularly neat and elegant. For instance: consider this code to insert an item into a simple linked list A binary tree, a simple type of branching linked data structure. ... In computer science, a linked list is one of the fundamental data structures used in computer programming. ...

 struct element { struct element *next; int value; }; struct element *head = null; void insert(struct element *item) { for(struct element **p = &head; *p!=null; p = &(*p)->next) { if(item.value <= (*p)->value) { break; } } item.next = *p; *p->next = item; } 

Support in various programming languages

A number of languages support some type of pointer, although some are more restricted than others. If a pointer is significantly abstracted, such that it can no longer be manipulated as an address, the resulting data structure is no longer a pointer; see the more general reference article for more discussion of these. This article discusses a general notion of reference in computing. ...


Ada

Ada is a strongly typed language where all pointers are typed and only safe type conversions are permitted. All pointers are by default initialized to null, and any attempt to access data through a null pointer causes an exception to be raised. Pointers in Ada are called access types. Ada 83 did not permit arithmetic on access types (although many compiler vendors provided for it as a non-standard feature), but Ada 95 supports “safe” arithmetic on access types via the package System.Storage_Elements. Ada is a structured, statically typed imperative computer programming language designed by a team led by Jean Ichbiah of CII Honeywell Bull during 1977–1983. ... Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of some condition that changes the normal flow of execution. ...


C and C++

In C and C++ pointers are variables that store addresses and can be null. Each pointer has a type it points to, but one can freely cast between pointer types. A special pointer type called the “void pointer” points to an object of unknown type and cannot be dereferenced. The address can be directly manipulated by casting a pointer to and from an integer. C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ... C++ (pronounced see plus plus, IPA: ) is a general-purpose, high-level programming language with low-level facilities. ...


C++ fully supports C pointers and C typecasting. It also supports a new group of typecasting operators to help catch some unintended dangerous casts at compile-time. The C++ standard library also provides auto_ptr, a sort of smart pointer which can be used in some situations as a safe alternative to primitive C pointers. C++ also supports another form of reference, quite different from a pointer, called simply a reference or reference type. C++ (pronounced see plus plus, IPA: ) is a general-purpose, high-level programming language with low-level facilities. ... auto_ptr is a template class available in the C++ Standard Library (declared in <memory>) that provides some basic RAII features for C++ raw pointers. ... A smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking. ... In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C, which is a reference in the general sense but not in the sense used by C++. // Syntax and terminology The declaration of the form <Type...


Pointer arithmetic, that is, the ability to modify a pointer's target address with arithmetic operations, is unrestricted: adding or subtracting from a pointer moves it by a multiple of the size of the datatype it points to. For example, adding 1 to a pointer to 4-byte integer values will increment the pointer by 4. This has the effect of incrementing the pointer to point at the next element in a contiguous array of integers -- which is often the intended result. Pointer arithmetic cannot be performed on void pointers because the void type has no size, and thus the pointed address can not be added to. In computer science, a datatype or data type (often simply a type) is a name or label for a set of values and some operations which one can perform on that set of values. ... The void type, in several programming languages derived from C, is the type for the result of a function that produces no direct result. ...


Pointer arithmetic provides the programmer with a single way of dealing with different types: adding and subtracting the number of elements required instead of the actual offset in bytes. In particular, the C definition explicitly declares that the syntax a[n], which is the n-th element of the array a, is equivalent to *(a+n), which is the content of the element pointed by a+n.


While powerful, pointer arithmetic can be a source of computer bugs. It tends to confuse novice programmers, forcing them into different contexts: an expression can be an ordinary arithmetic one or a pointer arithmetic one, and sometimes it is easy to mistake one for the other. In response to this, many modern high level computer languages (for example Java) do not permit direct access to memory using addresses. Also, the safe C dialect Cyclone addresses many of the issues with pointers. See C programming language for more criticism. A computer bug is an error, flaw, mistake, failure, or fault in a computer program that prevents it from working as intended, or produces an incorrect result. ... A programmer or software developer is someone who programs computers, that is, one who writes computer software. ... Java is an object-oriented applications programming language developed by Sun Microsystems in the early 1990s. ... The Cyclone programming language is intended to be a safe dialect of the C programming language. ... C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ...


The void pointer, or void*, is supported in ANSI C and C++ as a generic pointer type . A pointer to void can store an address to any data type, and, in C, is automatically casted to any other pointer type on assignment, but it must be explicitly casted if dereferenced inline. K&R C used char* for the “type-agnostic pointer” purpose. The C Programming Language, Brian Kernighan and Dennis Ritchie, one of the most read and trusted books on C. The C Programming Language (also known as K&R or the white book) is a famous computer science book which has been influential in the application and development of the C...

 int x = 4; void* q = &x; int* p = q; /* void* automatically casted to int*: valid C, but not C++ */ int i = *p; int j = *((int*)q); /* when dereferencing inline, there is no automatic casting */ 

C++ does not allow the automatic casting of void* to other pointer types, not even in assignments. This was a design decision to avoid careless and even unintended casts, though most compilers only output warnings, not errors, when encountering other ill casts.

 int x = 4; void* q = &x; // int* p = q; // This fails in C++: there is no autocast from void* int* a = (int*)q; // C-style cast int* b = static_cast<int*>(q); // C++ cast 

In C++, there is no void& (reference to void) to complement void* (pointer to void), because references behave like aliases to the variables they point to, and there can never be a variable whose type is void.


Perhaps the coup de grâce of void pointers is pointers to functions. Look up coup de grâce in Wiktionary, the free dictionary. ...

 int (*myfunc)(void); 

declares myfunc as a pointer to a function that accepts no arguments and returns an integer. It can be used in the following manner

 int the_y2k(void) { return 2000; } void main(void) { int (*myfunc)(void); int y; myfunc = the_y2k; y = myfunc(); } 

This declares myfunc as a pointer to the function the_y2k, calls the function, and assigns the returned value to y.


These are useful in creating dynamically linked library. In computer science, a library is a collection of subprograms used to develop software. ...


C#

In the C# programming language, pointers are supported only under certain conditions: any block of code including pointers must be marked with the unsafe keyword. Such blocks usually require higher security permissions than pointerless code to be allowed to run. The syntax is essentially the same as in C++, and the address pointed can be either managed or unmanaged memory. However, pointers to managed memory (any pointer to a managed object) must be declared using the fixed keyword, which prevents the garbage collector from moving the pointed object as part of memory management while the pointer is in scope, thus keeping the pointer address valid. The title given to this article is incorrect due to technical limitations. ... In computer science, garbage collection (also known as GC) is a form of automatic memory management. ...


The .NET framework includes many classes and methods in the System and System.Runtime.InteropServices namespaces (such as the Marshal class) which convert .NET types (for example, System.String) to and from many unmanaged types and pointers (for example, LPWSTR or void*) to allow communication with unmanaged code. Microsoft . ...


D

The D programming language is a derivative of C and C++ which fully supports C pointers and C typecasting. However D also offers numerous constructs such as foreach loops, out function parameters, reference types, and advanced array handling which replace pointers for most routine programming tasks. D is an object-oriented, imperative system programming language designed by Walter Bright of Digital Mars as a re-engineering of C/C++. He has done this by re-designing many C++ features, and borrowing ideas from other programming languages. ...


Fortran

Fortran-90 introduced a strongly-typed pointer capability. Fortran pointers contain more than just a simple memory address. They also encapsulate the lower and upper bounds of array dimensions, strides (for example, to support arbitrary array sections), and other metadata. An association operator, => is used to associate a POINTER to a variable which has a TARGET attribute. The Fortran-90 ALLOCATE statement may also be used to associate a pointer to a block of memory. For example, the following code might be used to define and create a linked list structure: Fortran (previously FORTRAN[1]) is a general-purpose[2], procedural,[3] imperative programming language that is especially suited to numeric computation and scientific computing. ...

  type real_list_t real :: sample_data(100) type (real_list_t), pointer :: next => null () end type type (real_list_t), target :: my_real_list type (real_list_t), pointer :: real_list_temp real_list_temp => my_real_list do read (1,iostat=ioerr) real_list_temp%sample_data if (ioerr /= 0) exit allocate (real_list_temp%next) real_list_temp => real_list_temp%next end do  

Fortran-2003 adds support for procedure pointers. Also, as part of the C Interoperability feature, Fortran-2003 also supports a intrinsic functions for converting C-style pointers into Fortran pointers and back.


Modula-2

Pointers are implemented very much as in Pascal, as are VAR parameters in procedure calls. Modula 2 is even more strongly typed than Pascal, with fewer ways to escape the type system. Some of the variants of Modula 2 (such as Modula-3) include garbage collection. Modula-2 is a computer programming language invented by Niklaus Wirth at ETH around 1978, as a successor to Modula, another language by him that was never implemented. ... This article or section does not adequately cite its references or sources. ...


Oberon

Much as with Modula-2, pointers are available. There are still fewer ways to evade the type system and so Oberon and its variants are still safer with respect to pointers than Modula-2 or its variants. As with Modula-3, garbage collection is a part of the language specification. Modula-2 is a computer programming language invented by Niklaus Wirth at ETH around 1978, as a successor to Modula, an intermediate language by him. ... Oberon is a reflective programming language created in the late 1980s by Professor Niklaus Wirth (creator of the Pascal, Modula, and Modula-2 programming languages) and his associates at ETHZ in Switzerland. ... This article or section does not adequately cite its references or sources. ...


Pascal

Pascal implements pointers in a straightforward, limited, and relatively safe way. It helps catch mistakes made by people who are new to programming, like dereferencing a pointer into the wrong datatype; however, a pointer can be cast from one pointer type to another. Pointer arithmetic is unrestricted; adding or subtracting from a pointer moves it by that number of bytes in either direction, but using the Inc or Dec standard procedures on it moves it by the size of the datatype it is declared to point to. Trying to dereference a null pointer, named nil in Pascal, or a pointer referencing unallocated memory, raises an exception in protected mode. Parameters may be passed using pointers (as VAR parameters) but are automatically handled by the runtime system. Pascal is an imperative computer programming language, developed in 1970 by Niklaus Wirth as a language particularly suitable for structured programming. ... In computer science, a datatype or data type (often simply a type) is a name or label for a set of values and some operations which one can perform on that set of values. ... In computer science, a datatype or data type (often simply a type) is a name or label for a set of values and some operations which one can perform on that set of values. ... KK Null, a Japanese musician Null, a special value in computer programming. ... Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of some condition that changes the normal flow of execution. ... Protected mode is an operational mode of x86-compatible CPUs of the 80286 series or later. ... A parameter is a variable which can be accepted by a subroutine. ...


PHP

PHP does not support pointers but it does support what is called "aliasing." For example: PHP (PHP:Hypertext Preprocessor) is a reflective programming language originally designed for producing dynamic web pages. ...

 <?php $a = 10; $b =& $a; ?> 

This declares $b as an alias to $a. While assignments to $b are visible through $a (and thus behave similarly to pointers), there are no explicitly pointers exposed to the PHP programmer and the alias forms a stronger bond than, say, C pointers. The only way to break the alias is to unset (destroy/delete) one of the variables:

 <?php $a = 10; $b =& $a; ... unset($a); ?> 

See also

In computer security and programming, a buffer overflow, or buffer overrun, is a programming error which may result in a memory access exception and program termination, or in the event of the user being malicious, a breach of system security. ... hazard pointer ... In computer programming, an opaque pointer is a datatype that hides its internal implementation using a pointer. ... In computer science, pointer swizzling is the conversion of references based on name or position to direct pointer references. ... This article discusses a general notion of reference in computing. ... Static analysis is the term applied to the analysis of computer software that is performed without actually executing programs built from that software (analysis performed on executing programs is known as dynamic analysis). ... In computer science a bounded pointer is a pointer that is augmented with additional information that enable the storage bounds within which it may point to be deduced. ...

External links

  • Pointer Fun With Binky Introduction to pointers in a 3 minute educational video - Stanford Computer Science Education Library (this link has crashed some browsers – use with caution)
  • 0pointer.de A terse list of minimum length source codes that dereference a null pointer in several different programming languages
  • A tutorial in C Pointers and Arrays by Ted Jensen


 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments
Please enter the 5-letter protection code

Want to know more?
Search encyclopedia, statistics and forums:

 


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms.