al said:
hi ,
whats the issue with the following declaration, is it correct and what
exactly is happening here.
int main()
{
//.....
int* ptr=10; // i suppose ptr is pointing to the memory location which
stores the value 10.
no, thats wrong and a big no-no.
You don't understand pointers.
//
......
}
on gcc it gives no error...but when i compile it using g++ it gives
"invalid conversion of int * to int"
please advise on this.
regards.
That is expected. You are inducing undefined behaviour.
You are not trying to *set* what is *at* the pointer to the value of
10.
You are trying to set the memory address *in* ptr to 10.
A very big no-no (thankfully caught by most C++ compilers).
This too is illegal:
int *ptr; // ptr holds some residual value, its unitialized (bad,
no-no, danger)
*ptr = 10;
How do you know what is at that residual location?
Imagine what happens when the compiler lets you overwrite any memory
location.
Answer: UB (format the hard drive, crash the computer, etc)
You think thats a common joke - but its not a joke
Pointers are always set using the address_of (&) operator or new.
int n; // reserve integer n on the stack, although n is uninitialized
int *ptr = &n; // reserve pointer ptr on stack & its now valid: it
holds n's address
*ptr = 10; // same as n = 10
Again, ptr holds an address, *ptr is the variable at that address.
And the term in question is "dereferencing the pointer".
One way or another, its the program that sets the pointer.
Pointers are not a toy, when you see a pointer, except for
polymorphism, a buzzer should go off in your head. Pointers are nearly
always bad news.
pointers are hell
pointers create bugs
pointers generate headaches
a pointer is a disease
etc
Stay away from pointers, use a reference instead.
hmm, how the hell are we going to explain references to you?