Monday, May 1, 2017

Function Pointer

Pointer to a function is declared as follows

void (*fn)()

Void is the return type
fn is the function name
() is the parameter types

For example

int (*abc)(int, int) is a function pointer for a function abc which accepts 2 integer arguments and returns an integer result

To use a function pointer

int sum(int a, int b)
{
    return a + b;
)

abc = sum;
z = abc(x, y);


Pointer Arithmatic.

Adding an integer, say i, to a pointer is actually advancing the pointer to i unit of the underlying data type the pointer points to.  For example,

int *p;
p = &j
p = p + 3;  /* p = p + 3*4 as integer is 4 bytes in length */

Likewise, for subtraction, the pointer is deducted by i units of the underlying data type.

When subtracting 2 pointers, the result is the number of units of the underlying data type.  A minus result indicate the first pointer is less than the second pointer in the expression.

Constant and Ponter

const int *p is a pointer to a constant integer.  We cannot change the variable that the pointer is pointing to but we can change the pointer to point to another variable.  However, even if the new variable it points to is not a constant, C runtime will not allow us to change it as it thinks the pointer is pointing to a constant as declared.

For example

const int *p;
const int i = 100
int j = 20

p = &i;  /* ok */
p = &j;  /* ok */
*p = 300;  /* error */

int *const p is a constant point pointing to an integer variable.  The pointer value cannot be change but we can change the variable it points to.

*p = 100;  /* ok */
p = &j;  /* error */

const int *const p is a constant pointer pointing to a constant variable. When the pointer is declard, it must be initialized.

const int *const p = &i

const int *const *p is a pointer to a constant pointer to a constant integer variable

Reading C Pointer Declaration

Reading the pointer declaration backward is easier.

For example, int * p

p = p is a variable
* = p is a pointer variable
int = p is a pointer variable points to an integer

const int * p = a pointer to an constant intege