A pointer is a data type whose value refers directly to (or "points to") another value stored elsewhere in the computer memory using its address.
A pointer is a language construct that allows a program to indirectly access memory: the pointer holds a memory address and provides operations to read and update that address.
The behavior of something called "pointer" depends on the programming language:
- C provides pointers that may be used to access arbitrary memory locations. While pointers are typed, it is easy to use a pointer of one type to access memory of a different type. It's also possible to store an arbitrary value in a C-style pointer; such a value may or may not reference a valid memory address, and attempting to dereference such a pointer may cause a segmentation fault.
- C++ provides C-style pointers, and also adds references. A C++ reference appears at the source level to be a simple variable (it does not require explicit dereferencing), but the generated code treats the variable as a pointer.
- Pascal provides a typed pointer; pointer variables may only be assigned with (1) the result of calling
New()
with the specified base type, or (2) from another variable of the specified pointer type. - Java, does not define a "pointer," but does define a reference that behaves in much the way as a Pascal "pointer."
Example: a C program that creates a pointer to an int
value, then accesses that value as if it were a float
. This is only possible with languages that support unrestricted, arbitrary pointers:
#include <stdio.h>
int main() {
int ival;
float* fptr;
ival = 1234567890;
fptr = (float*)&ival;
printf("%d as a double = %f\n", ival, *fptr);
}