Hi Friends,
Can we initialize a non-zero value to a pointer variable?
Ex : int *p=10;
Thanks in Advance!!!!
Printable View
Hi Friends,
Can we initialize a non-zero value to a pointer variable?
Ex : int *p=10;
Thanks in Advance!!!!
Sort of. You can do that, and it will make the pointer point to the memory address 10, which you don't own; thereafter, any attempt to use the pointer will result in disaster (unless you first make it point to somewhere "real").
Thanks Friend!!!
Also I want to know 2 more things..
Can i declare like this:
1) int *p = 0; // I guess p here would be a NULL pointer.
2) int *p, q;
p = &q;
p=4; // What will p contain?Is it a valid statement?
Thanks in Advance!!!!
Sorry, but no. You can't implicitly convert int to int*. You have to make an explicit conversion:
but you can do:Code:int* p = (int*)10;
or
int* p = reinterpret_cast<int*>(10);
But this is a different matter.Code:int* p = new int(10);
0 (zero) is the only literal constant allowed to be assigned to a pointer type.
Again you are trying to assign an integer to a pointer. p is a pointer, q is an integer (but avoid declaring a mixture of pointers and other types on a single line), so the first two lines are fine.Quote:
p=4; // What will p contain?Is it a valid statement?
What you can do is:
This means, set the value of the int that p points to (in this case q) equal to 4.Code:*p = 4;