+ 16
int *p; *p=&x; is wrong or right ? (x is previously declared) then whats the output
5 Respostas
+ 2
SRIKANT SAHOO
int *p - here you create a pointer;
when you initialize it, you do not need to prepend it with asterisk (*)
Here is more clear declaration of a pointer that will help you to understand, how it works:
int* p;
It is the same as int *p;
Asterisk is not a part of the variable's name.
In general, p gives the address of memory a pointer points to, while *p gives a value stored within.
+ 15
Ipang Steppenwolf Árpád Szabó
so in simple words if
int *p=&x; is possible
then why can't
int *p;
*p=&x; //as it can be thought of an
//assignment statement
isn't possible
and instead p=&x; is needed to be written?
+ 4
int *p = &x;
Two things happen in that line, first, you create int pointer, next you assign it a memory address, in this case the address in memory, allocated for int variable <x>.
int *p;
*p = &x;
You create int pointer, on the next line you assign reference of <x> (which is address of <x>) as a new value for the variable <x> by using the dereference operator. This means assigning an int pointer into an int variable, this triggers invalid conversion error. That's the reason why it didn't work.
Hth, cmiiw
+ 3
Tested the code in Code Playground, sorry to say, what you did there is not valid, I get invalid conversion on "*p=&x;" why? because you are assigning a variable x's address (int*) as data for pointer p (int).
0
int *p;
p = &x;
If you try to print out p, it will print x's value.
Explanation: p is a pointer to the memory address that stores the value of an x variable.