quest4tech.net |
|
POINTERS |
---|
A pointer is a variable that holds an address and can be incremented. It can be returned from functions to point to strings |
TERM | EXPLANATION |
---|---|
& | The address of |
* |
The value in the location pointed to by the address (which is in the word following the *). |
char *pav; | Defines pav as a pointer to type char (1 byte). |
pav = av; | Makes pav point to av (the address of the array). |
av[i] = 0; | Assign zero to the object that pav points at. |
void *vptr; | Create a generic pointer. |
long *mem_ptr; | Create a pointer that is of type long (int). |
mem_ptr = (long *)saddr; | Put address into the pointer. |
*mem_ptr = sval; | Put data, sval, into the address given by mem_ptr. |
int *devaddr; | Defines devaddr as a pointer to an object type int. |
devaddr = 0xFF0A; | Address of a device. |
(char *)incoming_data | Gives start of the incoming data field. |
Program example of checking the status word of a device using pointers. |
---|
The example shows the use of a mask Hex. 0x4 to find out if bit 3 in the location pointed to by statusaddr is ON or OFF. For other bits, replace Hex. 0x4 with their Hex. equivalent. |
int status; | // set up variable for status word | |
int *statusaddr; | // set up pointer for address of status word | |
statusaddr = &status; | // put address of status word into pointer |       |
// use status word to hold status of a device |       | |
if (*statusaddr & 0x4) | // is bit 3 set to a '1' in the data at address given by the pointer | |
   printf("\nBit 3 is ON."); | // bit 3 is a '1' | |
else | ||
   printf("\nBit 3 is OFF."); | // bit 3 is a '0' |
TERM | EXPLANATION |
---|---|
char av[10] | Reserves space for 10 chars (= 10 bytes), from av[0] through to av[9]. |
extern | Enables a variable to be declared without defining it.
For example: extern int a; instead of int a = 1; |
typedef | Declares a new name for a type. For example: typedef char* Pchar; Pchar p1, p2; char* p3 = p1; |
static | A static variable is one that is initialised only once, on its first pass. If no value is given, it is initialised to zero in its first pass. |
void | Self contained function with no need for input or output data. |
de-reference | De-reference a pointer with an * i.e. refer to the value that it points to. The asterisk is the de-referencing operator. |
TERM | EXPLANATION |
---|---|
list.a | The value of field a in the structure list. |
list_ptr->a | The value of field a in the structure at the address list_ptr. |
Passing by value and passing by reference (i.e. using a pointer) |
---|
When passing a value, you pass a copy of that value. When you passing by reference, you pass the address, thereby giving the receiver direct access to the data at that address. |
(c) Compiled by A J & B V Wood. |