Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing pointers in C++

Can assign a pointer to a value on declaration? Something like this:

    int * p = &(1000)
like image 304
Alex Avatar asked May 22 '09 22:05

Alex


People also ask

How is a pointer initialized in C?

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 initializing a pointer?

Pointer Initialization is the process of assigning the address of a variable to a pointer. In C language, the address operator & is used to determine the address of a variable.

Can we initialize a pointer in C?

Initialization of C Pointer variablePointer Initialization is the process of assigning address of a variable to a pointer variable. Pointer variable can only contain address of a variable of the same data type. In C language address operator & is used to determine the address of a variable.

Do you need to initialize a pointer?

All pointers, when they are created, should be initialized to some value, even if it is only zero. A pointer whose value is zero is called a null pointer. Practice safe programming: Initialize your pointers!


1 Answers

Yes, you can initialize pointers to a value on declaration, however you can't do:

int *p = &(1000);

& is the address of operator and you can't apply that to a constant (although if you could, that would be interesting). Try using another variable:

int foo = 1000;
int *p = &foo;

or type-casting:

int *p = (int *)(1000); // or reinterpret_cast<>/static_cast<>/etc
like image 165
Adam Markowitz Avatar answered Sep 28 '22 21:09

Adam Markowitz