failing like never before

25Mar/080

Passing an Array in C

This quick little article is intended to give you a better idea of how arrays are passed in C. A basic understanding of pointers is required. If you don't know what pointers are, check them out at wikipedia.

We'll be using the following array as an example throughout the article:

char c_array[50];

The variable that we use to reference the array is actually a pointer. A pointer points to a location in the computer's memory, as you probably already know. You can have pointers to any data type you want, even a pointer to a pointer. The reason why we can reference all 50 elements of our array with just one pointer, is because arrays are allocated as one big fat chunk of memory. That is, all the elements in the array are lined up in the computer's memory one after the other. This is very handy, because if we know the location of the zero element in the array (the pointer to an array points to the zero element) we can get the physical location in memory of the fifth element (I made a funny!) by doing something like:

c_array + 4

Of course, thats a rather impractical way of accessing data, so we usually just end up doing:

c_array[4]

(Notice that I used a 4 to access the fifth element, because in Computer Science we always begin counting from 0, and not 1)

The fact that arrays are referenced by pointers, can be both good and bad. If your array is quite large, then passing by value can be quite expensive (that is, if you could pass an array by value, arrays in C have to be passed by reference). However, as you probably know, passing by reference can be a problem because you may want to leave your old array untouched. When passing an array, if you want to make sure your passed array isn't changed or modified you can either pass it as const, or else create a new array and copy all your old data into it. You can use strcpy from the standard library to copy the array into a new one.