Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I value-initialize a Type* pointer using Type()-like syntax?

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?

like image 226
sharptooth Avatar asked Nov 09 '11 15:11

sharptooth


People also ask

How do you initialize a pointer value?

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 .

What is the syntax of declaring and initializing a character pointer?

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.

How do you initialize a pointer example?

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 .

What does * mean in pointer?

The asterisk * used to declare a pointer is the same asterisk used for multiplication.


1 Answers

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.).

like image 198
Jerry Coffin Avatar answered Oct 14 '22 13:10

Jerry Coffin