If I write the code :
int i ;
I am declaring an integer variable called i. It can hold an integer value within the range for this version of C.
If I write the code :
int * ptr ;
I am declaring a pointer to an integer. This looks very confusing. The only time that we have seen * used has been when we perform multiplication. However, in this context the meaning of * is quite different. In this case we are declaring a pointer, which I have called ptr. The compiler is quite happy with this dual use of the * character, in that it can easily tell what the programmer means. If the * follows the name of a type, it must be creating a pointer. You will have to learn to live with this if you want to use pointers.
The variable ptr is allowed to point at (or hold the address of) an integer value. I make ptr point at a variable by finding out its address and setting ptr to this:
ptr = &i ;
If this looks frightening, you are not alone. The use of the & character in this way is very strange, in that you have only ever seen this character used for performing the AND operation. However, if the compiler sees & given before a variable name like this it interprets it as meaning "the address of that variable". Since that is exactly what we need to give ptr to make it point at i, all is well. You can get the address of any variable by putting an & character in front of the name in your program. This assignment is shown in the diagram on the right.
Note that C will let you set ptr to any number you like, which makes the pointer point at that number location in memory. This can sometimes be useful if you want to control hardware which "lives" at a particular place in the address space.
XC8 lets you declare variables as "living" at a certain position in memory. Remember that when you use this feature you are trying to do something highly specific and will know what you are doing. This is not standard C however, but if we wanted to write standard C we would not be using a PICmicro!
char portb@0x06 ;
The number which follows the @ character identifies the location in memory which is to hold the variable. Note that I have expressed the address in hexadecimal. Now, whenever I change the contents of the variable portb I will be changing the contents of memory location number 6, which happens to be where portb in the PICmicro lives!
ptr equals the location of i.