In C Programming, you will have to use a new type of variable called a pointer. All a pointer does is store the address of another variable. It is basically like a shortcut or an alias to another part of memory. You can use pointers for many variable types including integers, floats, strings and structures. Structures are used a lot in some operating systems including the Amiga. So, if a structure is defined elsewhere in memory then you need to have a pointer to it.
So, to get the address of something, you use the ampersand (&) character e.g. &mywindow.
To define a pointer you use the asterick (*) character e.g. *mypointer.
A simple integer pointer can be created like this:
int num; /* Integer variable called num */ int *num_ptr; /* A pointer of type int, called num_ptr */
num = 150; /* Assign value of 150 to num */ num_ptr = # /* Get the address of num and store it in num_ptr */
printf("%d\n", *num_ptr); /* Print value of *num_ptr and you will get 150! */
For example, if you have structure called vehicle:
struct vehicle { char make[25]; char model[25]; char vehicletype[25]; float enginesize; int cylinders; bool turbocharge; bool supercharge; }
I can then create an instance of that vehicle and specify a name of that vehicle:
struct vehicle aston_martin;
aston_martin.make = "Aston Martin"; aston_martin.model = "DB9"; aston_martin.vehicletype = "Car"; aston_martin.enginesize = 6.2; aston_martin.cylinders = 12; aston_martin.turbocharge = false; aston_martin.supercharge = false;
Now, I can create a pointer to my structure as follows, note that thee asterick is not required on the left side of the assignment statement.
struct vehicle *myvehicle; /* Create a pointer of type vehicle called myvehicle */
myvehicle = &aston_martin; /* Assign the address of aston_martin to the pointer myvehicle */
Now, to access individual items of the structure, I cannot use the name dot item format anymore, I have to use a special structure pointer, -> (dash, right arrow):
float engine; engine = *myvehicle->enginesize; /* Get the value of the enginesize from the vehicle pointed to by myvehicle. Since myvehicle is pointing the aston_martin, it will be 6.2 */
This is the equivalent of the statement:
float engine; engine = aston_martin.enginesize; /* Get the engine size from the vehicle structure instance called aston_martin, ie 6.2 */
String variables are naturally pointers so if string variable called name is used, its address can be access by either &name or just name (no ampersand).