Книга: Advanced PIC Microcontroller Projects in C

3.1.15 Pointers

3.1.15 Pointers

Pointers are an important part of the C language, as they hold the memory addresses of variables. Pointers are declared in the same way as other variables, but with the character (“*”) in front of the variable name. In general, pointers can be created to point to (or hold the addresses of) character variables, integer variables, long variables, floating point variables, or functions (although mikroC currently does not support pointers to functions).

In the following example, an unsigned character pointer named pnt is declared:

unsigned char *pnt;

When a new pointer is created, its content is initially unspecified and it does not hold the address of any variable. We can assign the address of a variable to a pointer using the (“&”) character:

pnt = &Count;

Now pnt holds the address of variable Count. Variable Count can be set to a value by using the character (“*”) in front of its pointer. For example, Count can be set to 10 using its pointer:

*pnt = 10; // Count = 10

which is the same as

Count = 10; // Count = 10

Or, the value of Count can be copied to variable Cnt using its pointer:

Cnt = *pnt; // Cnt = Count

Array Pointers

In C language the name of an array is also a pointer to the array. Thus, for the array:

unsigned int Total[10];

The name Total is also a pointer to this array, and it holds the address of the first element of the array. Thus the following two statements are equal:

Total[2] = 0;

and

*(Total + 2) = 0;

Also, the following statement is true:

&Total[j] = Total + j

In C language we can perform pointer arithmetic which may involve:

• Comparing two pointers

• Adding or subtracting a pointer and an integer value

• Subtracting two pointers

• Assigning one pointer to another

• Comparing a pointer to null

For example, let’s assume that pointer P is set to hold the address of array element Z[2]:

P = &Z[2];

We can now clear elements 2 and 3 of array Z, as in the two examples that follow. The two examples are identical except that in the first example pointer P holds the address of Z[3] at the end of the statements, and it holds the address of Z[2] at the end of the second set of statements:

*P = 0;    // Z[2] = 0
P = P + 1; // P now points to element 3 of Z
*P = 0;    // Z[3] = 0

or

*P = 0;       // Z[2] = 0
*(P + 1) = 0; // Z[3] = 0

A pointer can be assigned to another pointer. In the following example, variables Cnt and Tot are both set to 10 using two different pointers:

unsigned int *i, *j;   // declare 2 pointers
unsigned int Cnt, Tot; // declare two variables
i = Cnt;               // i points to Cnt
*i = 10;               // Cnt = 10
j = i;                 // copy pointer i to pointer j
Tot = *j;              // Tot = 10

Оглавление книги


Генерация: 2.665. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз