I'm not sure if I can ask basic questions here, but I am starting to learn C++ and do not understand one little thing in pointers syntax.
Here is the sample of my code:
using namespace std;
int randomname(int *x);
int main(){
int a = 1;
int *ab;
ab = &a;
randomname(&a);
}
int randomname(int *x){
*x = 9001;
}
My question is about the * symbol. Why in the main function on line ab = &a; I don't need the *, but on line *x = 9001; I need it? I think syntax should be same in both functions, but it isn't. Can someone please explain why?
The meaning of both the asterisk * and the ampersand & changes depending on the context. Their meanings in expressions and in declarations are different:
* is used in a declaration, it designates a pointer& is used in a declaration, it designates a reference* is used in an expression, it performs a pointer dereference of its operand& is used in an expression, it obtains a pointer of its operandOnce you understand these distinctions, you can tell that
int *ab is a declaration. Asterisk designates ab as a pointer.ab = &a; has an expression. & takes a's pointer, and assigns it to ab, which has a pointer type specified at the time of its declaration (above).*x = 9001 is also an expression, making the asterisk a dereference operator. You use the asterisk to tell the compiler that the target of the assignment is whatever is pointed to by x, not x itself.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With