PROGRAMMING PIC MICROCONTROLLERS IN C:POINTERS IN C

POINTERS IN C

Pointer are widely used in C programs. A pointer is a variable which stores the address of another variable. A pointer is declared by preceding it with the ‘*’ character. For example, a character pointer called p is declared as follows:

char *p;

Similarly, an integer pointer called pnt is declared by writing:

int *pnt;

In the above example, although pnt is declared as a pointer, currently it is not assigned any value. The address of a variable is obtained by preceding the variable name with the ‘&’ character. For example, the address of the integer variable sum is obtained as follows:

pnt = ∑

We can also make the above declaration by writing:

int *pnt = ∑

Now, the pointer pnt holds the address of the variable sum. We can access the value of a variable whose address is known by preceding its pointer with the ‘*’ character. Thus, in the above example, we can set the value of the variable sum to 10 as follows:

*pnt = 10;

In C whenever variables are passed as arguments to a function, their values are copied to the corresponding function parameters, and the variables themselves are not changed in the calling environment. This is referred to as the call-by-value mechanism. Most other languages provide call-by-reference mechanisms so that the values of variables can be changed in functions. In C this is done using pointers where the addresses of the variables are passed to a function and not their values. An example function is given below which swaps the values of two of its arguments:

Programming PIC Microcontrollers in C-0136

Either of these definitions is independent of the size of the array being passed, and the array size is in general not known by the function. In a function definition, a formal parameter that is defined as an array is actually a pointer. When an array is passed as an argument to a function, the base address is passed and the array elements themselves are not copied. An array bracket notation is used to declare pointers as parameters. An example is given below where it is assumed that array a has 10 elements:

Programming PIC Microcontrollers in C-0137

Programming PIC Microcontrollers in C-0138

Leave a comment

Your email address will not be published. Required fields are marked *