It looks like you've got the first part right.
An incidental thought: there are various conventions about where to put that *
sign. I prefer mine nestled with the variable name, as in int *test1
while others prefer int* test1
. I'm not sure how common it is to have it floating in the middle.
Another incidental thought: test2 = 3.0
assigns a floating-point 3 to test2
. The same end could be achieved with test2=3
, in which case the 3 is implicitly converted from an integer to a floating point number. The convention you have chosen is probably safer in terms of clarity, but is not strictly necessary.
Non-incidentals
*test1=3
does assign 3 to the address specified by test
.
test1=3
is a line that has meaning, but which I consider meaningless. We do not know what is at memory location 3, if it is safe to touch it, or even if we are allowed to touch it.
That's why it's handy to use something like
int var=3;
int *pointy=&var;
*pointy=4;
//Now var==4.
The command &var
returns the memory location of var
and stores it in pointy
so that we can later access it with *pointy
.
But I could also do something like this:
int var[]={1,2,3};
int *pointy=&var;
int *offset=2;
*(pointy+offset)=4;
//Now var[2]==4.
And this is where you might legitimately see something like test1=3
: pointers can be added and subtracted just like numbers, so you can store offsets like this.
&test1
is a pointer to a pointer, but that sounds kind of confusing to me. It's really the address in memory where the value of test1
is stored. And test1
just happens to store as its value the address of another variable. Once you start thinking of pointers in this way (address in memory, value stored there), they become easier to work with... or at least I think so.
I don't know if *test2
has "meaning", per se. In principle, it could have a use in that we might imagine that the *
command will take the value of test2
to be some location in memory, and it will return the value it finds there. But since you define test2
as a float, it is difficult to predict where in memory we would end up, setting test2=3
will not move us to the third spot of anything (look up the IEEE754 specification to see why). But I would be surprised if a compiler would allow such thing.
Let's look at another quick example:
int var=3;
int pointy1=&var;
int pointy2=&pointy1;
*pointy1=4; //Now var==4
**pointy2=5; //Now var==5
So you see that you can chain pointers together like this, as many in a row as you'd like. This might show up if you had an array of pointers which was filled with the addresses of many structures you'd created from dynamic memory, and those structures contained pointers to dynamically allocated things themselves. When the time comes to use a pointer to a pointer, you'll probably know it. For now, don't worry too much about them.