next up previous
Next: structs Up: Arrays, Pointers, and structs Previous: Arrays


Pointers are very powerful but also very dangerous. As you can see from the previous example, there's nothing stopping myfunc() from trying to write to element 99 of myarray. Doing so would at best result in a ``segmentation fault'' error. At worst, your program could be corrupted in unpredictable ways as it's running, leading to nonsensical results. To avoid the headache of tracking down seg faults, learn to be paranoid about pointers. Here's a much more careful version of the previous program:

    #include <stdio.h>
    #include <assert.h>

    void init_array(int *myarray,int nelem,int elem,int val)
        assert(myarray != NULL);
        assert(elem >= 0 && elem < nelem);
        myarray[elem] = val;

    #define MAX_NELEM 15

    void main(void)
        int myarray[MAX_NELEM];

Here we used assert()s to ensure first that the pointer has a non-zero value and second that no attempt is made to access the array out of bounds.

Generally pointers are used to allow a function to modify the contents of a memory address. This can make for very elegant code, and indeed is the only way for a function to change the value of a passed scalar, but it pays to be careful when using them.

Massimo Ricotti 2009-01-26