In C++, a pointer is an object whose value is the memory address of another object. In other words, a pointer is a variable which stored the memory address of another variable.
A pointer references a location in memory. When declaring a pointer, the type of the pointed-to variable must be specified:
Specifying type when declaring a pointer is necessary because when the pointer is dereferenced (i.e. the pointed-to value is accessed) the type needs to be known.
To access the value held in the memory address held by a pointer, the pointer is dereferenced using the
* operator - the same operator used to declare a pointer variable:
…the following holds:
||Returns the address that
||Returns the pointer’s own address, the address of
||Dereference the pointer
||Return the address of
||Dereference the address of ptr - return the value held in the address of
||Dereference the address of
Pointer to Pointer
Pointers generally contain the memory address of a variable - but they can also contain the address of another pointer.
Using a pointer-to-pointer as a function parameter makes it possible to modify values within a function with those values persisting outside the function.
It is not likely that you need to use pointer-to-pointer type structures in modern C++ code. References are available for passing to a function by reference rather than value, and rather than pointing to an array of strings, it’s probably better to use
std::vector<std::string>. However, the
char ** notation does pop up - I recently saw this while researching the C
getopt() function - in which an example showed arguments to the
main() function are presented as
char **argv, rather than the more common char
Pointer to Pointer/Pointer to char * array Equivalence
A sequence of strings can be passed to
main() as an argument, if the main function is able to receive them.
main() the capacity to receive arguments by adding two parameters to the function - an
int and a pointer to
The following are equivalent:
char *argv is read ‘declare argv as array of pointer to char’, and the array argument is demoted to a pointer to the first element in that array,
char *argv is equivalent to
char **argv - which is read as: ‘declare argv as pointer to pointer to char’
comments powered by Disqus