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

Arrays

In C, you can make an array (e.g., of integers) in one of two ways: with a declaration at the start of the function like int myarray[N];, where N is the number of elements in the array, or by declaring a pointer int *myarray; and calling malloc() to allocate N ints to it (see section [*]). In either case, you reference element n in the array as myarray[n], noting that array indices start at 0 in C, not 1. Regardless of how you declared the array, the name of the array (in this case myarray) is always a pointer to the first element, and can be passed as a pointer to another function. This means a function that is passed an array can modify the contents of the array, since it knows exactly where in memory the data is stored. As an example,

    void init_array(int *myarray)
    {
       myarray[0] = 12;
    }

    void main(void)
    {
       int myarray[15];
       init_array(myarray);
    }

declares an array and calls a function to initialize the first element of it. Note that myfunc() does not know the size of the array; usually you would pass this information as well, otherwise you risk accessing the array out of bounds.


next up previous
Next: Pointers Up: Arrays, Pointers, and structs Previous: Arrays, Pointers, and structs
Massimo Ricotti 2009-01-26