Mikroc – ABL electronic PIC Microcontrollers PIC16 User Manual

Page 80

Advertising
background image

You can also compare pointers to zero value – this tests if pointer actually points
to anything. All pointers can be successfully tested for equality or inequality to
NULL:

if

(pa == NULL) { ... }

if

(pb != NULL) { ... }

Note: Comparing pointers pointing to different objects/arrays can be performed at
programmer’s responsibility — precise overview of data’s physical storage is
required.

Pointer Addition

You can use operators

+

,

++

, and

+=

to add an integral value to a pointer. The

result of addition is defined only if pointer points to an element of an array and if
the result is a pointer pointing into the same array (or one element beyond it).

If a pointer is declared to point to

type

, adding an integral value to the pointer

advances the pointer by that number of objects of type. Informally, you can think
of

P+n

as advancing the pointer

P

by

(n*sizeof(

type

))

bytes, as long as the

pointer remains within the legal range (first element to one beyond the last ele-
ment). If

type

has size of 10 bytes, then adding 5 to a pointer to

type

advances

the pointer 50 bytes in memory. In case of

void

type, size of the step is one byte.

For example:

int

a[10];

// array a containing 10 elements of int

int

*pa = &a[0];

// pa is pointer to int, pointing to a[0]

*(pa + 3) = 6;

// pa+3 is a pointer pointing to a[3],
// so a[3] now equals 6

pa++;

// pa now points to the next element of array, a[1]

There is no such element as “one past the last element”, of course, but a pointer is
allowed to assume such a value. C “guarantees” that the result of addition is
defined even when pointing to one element past array. If

P

points to the last array

element,

P+1

is legal, but

P+2

is undefined.

mikroC - C Compiler for Microchip PIC microcontrollers

mikroC

making it simple...

72

MikroElektronika: Development tools - Books - Compilers

page

Advertising
This manual is related to the following products: