What Is the Dereference Operator?
The dereference operator is a symbol used in computer programming to retrieve a value located at a specific memory address. The operator, usually represented by an asterisk in the source code, is applied before a variable that is pointing to a memory address, or pointer. Sometimes called the indirection operator, it also can be used when declaring or initializing variables to indicate that they are pointers to a data type and not the data type itself. When determining the order of operations, the dereference operator takes precedence over nearly all standard mathematical operators.
To understand what this operator does, it is important to understand how data types in computer programming work. A variable in a program can hold a value. Many times, this is simply an integer or a string of characters. Other times, it can be a memory address that is pointing to an integer value. Variables that hold memory addresses are called pointers.
When it is necessary to assign, modify or retrieve the data that is stored at the memory address a pointer contains, the dereference operator must be used. If a mathematical operation, such as addition, is done to a pointer variable without dereferencing it, then the operation will be performed on the memory address and not the variable to which it is pointing. There are times when arithmetic operations performed on memory addresses can enhance efficiency, as in the case of stepping though an array, which is why this functionality exists. When the dereference operator is used on a pointer, all operations will be performed on the data that is stored at the memory location and not the memory address itself.
The operator also can be used when initially declaring a new variable. By placing the operator between the variable type and the variable name, it will indicate that the new variable should be a pointer to a data type and not just an instance of the type. Variables that are created in this fashion need to be initialized with some type of memory allocation function, because the pointer will need to be set to an unused memory location by the memory manager the program is using.
There are some hazards that need to be avoided when using the dereference operator. Most notably is attempting to dereference a pointer that is null or undefined. The pointer technically does not have a memory address, so different errors or exceptions will be generated that will stop execution of a program. Null-safe versions of the dereference operator exist that will not cause an error, but these operators have a different syntax.
Discuss this Article
Post your comments