For the first line, you're attempting to assign an address to an int, which is a no-no. (An address, while represented by an integer, is not an integer.)
In the second line, you're trying to assign a pointer to an int, also bad.
Third part is the same explanation as the first.
If you want to define an alias to a variable, use this notation:
thanks Moschops and atropos.
this concept is not sinking in for me.
i am confused by the use of * and &.
i thought that if i wanted to indicate the address of num1, i would write &num1. and if i wanted to indicate the value in num1, i would write *num1.
but it looks like this labeling is different from int *num1. what does int *num1 indicate then? an address? or a value?
what does int *num1 indicate then? an address? or a value?
int * num1; declares a pointer-to-int called 'num1'.
example:
1 2 3 4 5 6 7
//...
int num = 2; //integer variable defined
int * ptr = NULL; //pointer-to-int declared and initialized to NULL (it's good practice to initialize all variables)
ptr = # //OK, since '&num' is the address(pointer) to 'num'
std::cout << "Num is: " << num << std::endl; // displays '2'
std::cout << "Ptr points to: " << *ptr << std::endl; // displays value pointed to by ptr, which is the value of num (which of course, is '2')
std::cout << "Num is at memory address: " << ptr << std::endl; //displays the address of 'num'
What you're talking about is what gets most people confused when they first get into pointers.
1 2
int *ptr = &bar;
*ptr = 12;
The two astericks (*) there are simply just the same symbol used for different tasks. They mean different things, and do different things. Why they did this? I don't know, but it tends to confused people.
Anyway, line one is just a pointer declaration and initialization (you should always initialize your pointer right away). The second line is what's called dereferencing the pointer, using that same asterik, and what that does is returns the value at the address that the pointer is pointing. In this case, it returns the value that bar holds.
thank you ResidentBiscuit, LowestOne, atropos and Moschops.
extremely helpful.
it seems more logical to me to define the pointer with the * after the int, rather than before the name... as in int* ptr rather than int *ptr.
anyway, thanks.