Variables of built-in types can be value-initialized like this:
int var = int();
this way I get the default value of int
without hardcoding the zero in my code.
However if I try to do similar stuff for a pointer:
int* ptr = int*();
the compiler (Visual C++ 10) refuses to compile that (says type int unexpected
).
How do I value-initialize a pointer in similar manner?
You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator ( & ). The address-of operator ( & ) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number .
The syntax of declaring a pointer is to place a * in front of the name. A pointer is associated with a type (such as int and double) too. Naming Convention of Pointers: Include a "p" or "ptr" as prefix or suffix, e.g., iPtr, numberPtr, pNumber, pStudent.
The initializer is an = (equal sign) followed by the expression that represents the address that the pointer is to contain. The following example defines the variables time and speed as having type double and amount as having type pointer to a double .
The asterisk * used to declare a pointer is the same asterisk used for multiplication.
Use a typedef to make a name for your pointer type:
typedef int *ip;
ip ptr = ip();
The same idea should work for other types that require more than one lexical element (word) to define the name of the type (e.g., unsigned long
, long long
, unsigned long long *
, etc.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With