Variables can be declared to be pointers to items of any type by using the asterix syntax we saw for reference parameters. Note that a pointer to a type can refer to a single variable or to an array of that type. The pointer to an array is also a pointer to the first item of that array. The following are examples.
char * s1: /* pointer to a char or an array of chars */ char ** sp1; /* pointer to a pointer of chars or to an array of pointers to chars etc. */The declaration of a pointer to a type can be mixed with declarations to variables of that type, since the pointer operator, *, is right associative.
int i1, * ip1, i2, *ip2; /* i1 and i2 are int, ip1 and 1p2 are pointer to int */When using pointers to structs or unions, it is sensible to exploit typedefs to make the program more readable.
struct pr { int val1; float val2; }; struct pr * prp1; typedef struct pr prs; prs * prp2; typedef struct pr * prp; prp prp3;prp1, prp2 and prp3 are all pointers to structs of type pr. A pointer to a certain type can be assigned the address of a variable of the same type by using the address operator (or referencing operator) &.
int i; int * ip; ip = & i; /* ip points at the location of i */The contents of the variable pointed to by a pointer can be accessed by using the dereferencing operator, *.
*ip = 3; /* set the value in i to 3, via ip */ printf("%d\n",*ip); /* print out the value in i, via ip */