views:

473

answers:

5

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

    int * p = &(1000)
A: 

Yes. However if its a class member you have to do it in the constuctor. If it is a static member, you have to do it where it is defined, not where it is declared (unless they are the same place of course). Assigning 0 to a member where it is declared is used to tell the compiler that it is a virtual member.

T.E.D.
+11  A: 

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
Adam Markowitz
Are string constants a special case? Though that would need to be a "const char *"...
dmckee
Yes, string literals are special in that they are lvalue expressions, referring to an array object (not a pointer). So you can do 'char const(*p)[3] = ' Not less interesting is initializing a char const* like this: 'char const *p = '
Johannes Schaub - litb
+1  A: 

Um. I don't think you can take a non-const address of a constant like that.

but this works:

int x = 3;
int *px = &x;
cout << *px; // prints 3

or this:

const int x = 3;
const int *px = &x;
const int *pfoo = reinterpret_cast<const int*>(47);
Marcus Lindblom
A: 

What about:

// Creates a pointer p to an integer initialized with value 1000.
int * p = new int(1000);

Tested and works. ;-)

TomWij
But don't forget to delete!
GMan
+3  A: 

There are two things not clear in the question to me. Do you want to set the pointer to a specific value (i.e address), or do you want to make the pointer point to some specific variable?

In the latter case, you can just use the address-of operator. The value of the pointer is then set to the address of some_int_variable.

int *p = &some_int_variable;
*p = 10; // same as some_int_variable = 10;


Note: What follows is evil changing of the pointer's value manually. If you don't know whether you want to do that, you don't want to do it.

In the former case (i.e setting to some specific, given address), you can't just do

int *p = 1000;

Since the compiler won't take the int and interpret it as an address. You will have to tell the compiler it should do that explicitly:

int *p = reinterpret_cast<int*>(1000);

Now, the pointer will reference some integer (hopefully) at address 1000. Note that the result is implementation defined. But nevertheless, that are the semantics and that is the way you tell the compiler about it.

Update: The committee fixed the weird behavior of reinterpret_cast<T*>(0) that was suggested by a note and for which i provided a workaround before. See here.

Johannes Schaub - litb