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.

I think by know, you should have a fairly deccent understanding of how passing of arrays work in C. Below, is a quick example of how it all works out.

int mod_array(int* i_array);

int main()
{
     int i_array[12];
     i_array[2] = 12;
     i_array[5] = 34;
     mod_array(i_array);
     return 1;
}

int mod_array(int* i_array)
{
     printf("third element: %d\n", i_array[2]);
     printf("sixth element: %d\n", i_array[5]);
     return 1;
}

And, as you might have guessed, this will print out:

third element: 12
sixth element: 34

I hope this helped, if you feel like this article sucked, or you require additional illumination. Leave a comment and I'll try to respond as soon as I can.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


Security Code:

Trackbacks are disabled.