Tuesday, July 17, 2007

Pointer

* Data Type For Pointer
In general, a pointer is of UNSIGNED LONG int, which means the pointer has sizeof(unsigned long) bytes.

* Initialize Pointers First
Pointers should be initialized after declaration, with &, malloc or NULL. Keep in mind this rule when deal with multi-dimension pointers. The following is a typical example:
char *p = "Hello World";
char **pp; /* No initialization here */
*pp = p;

The usage of **p in this example is a little bit special:
void GetMem(char **p, size_t num)
{
     *p = (char *)malloc(num * sizeof(char));
}
The caller must initialize p first with &, then pass it to this subroutine. No way to guarantee that p is valid within the subroutine. Otherwise the result of dereferencing p is undefined.

Another way to initialize pointers is:
int *p = (int *)0x12345678;
*p = 1; == *((int * const)0x12345678) = 1;

* Check Pointers Before Use Them
Dereferencing a NULL pointer or an illegal but not NULL pointer is undefined. Therefore checking if it is NULL is always the first thing for pointers as function input parameters or return value.

* The Precedence of Symbol `*'
The symbol `*' has lower precedence than postfix operators, like `.', ->, (), [], ++, --, etc. Keep this in mind to understand the correct meaning of some expressions:
*p.f, *a[0], *fp(), *p++

* Pointer Operations
- Subtraction is meaningful for two pointers while addition is not when both are doing with the same memory region, like array or buffer.
- When one constant is added/subtracted to a pointer, the resulting address is not just the addition/subtraction of them. It depends on the type of pointer and is calculated by the compiler.

* Operator []
When use a pointer to an array or memory block(allocated with malloc), p[i] and p+i is totally different. p[i] is dereferenced and not a pointer any more.

* Exchangeable Pointer and Array Name
As mentioned before, the array name actually is a pointer of data type of array's elements for most of time. So a pointer could be one to a single variable, to an array or to a memory region.
    int a[3][5];
    int (*p)[5];
    p = a; =>
    p[2][5] == a[2][5]
On the other hand, be careful about this:
    int a[3];
    int (*p)[3];
    p = &a; =>
    (*p)[2] == a[2]

* Print Address
    printf("The value of the pointer is %p\n", (void *)p);

No comments: