Popular Posts

Thursday, July 16, 2009

Arrays in C

Arrays

Arrays in C are a very powerful way to access data, because they are contiguous memory sequences and they allow random access to their contents. What's more, array variables are actually pointers to the beginning of the contiguous memory block. There are two ways to access an array depicted in file arrays.c:

Indexed reference with brackets: a[cnt] = 'a' + cnt;

This is the common way to access an array, and it is by far the most intuitive way. The variable cnt simply denotes the index of an array element in array a.

Pointer arithmetics: *(a + cnt) = 'b' + cnt;

Because the arrays in C are always contiguous, it is possible to access their elements by incrementing the array pointer by the index value and referring to the element.

You can define an array with a constant size using the bracket notation: int a[15];. Some C compilers are also happy with the following notation: int *a = {1, 2, 3, 0};. Strings in C are char arrays and practically all compilers can deal with the following type of declaration: char *name = "Copernicus";, which creates a char array of length 11, last element being a NULL character. ALL STRINGS IN C MUST END IN A NULL CHARACTER!

You can use multi-dimensional arrays in C. Arrays are indexed in row-major style and you have to be careful about how your program walks through the indexes.

int a[20][4];

That code block defines an 20-row array of four-number arrays. Using pointer arithmetic, you can access row 3, column 2 like this:

int row = 3;
int col = 2;
int val = *(a + ((row * 4) + col));

In some programs the command line is processed by looking at the parameters defined in the main function. First parameter contains the number of arguments that have been passed to the program and as we take two values from the command line, it should be equal or higher than two. The second parameter seems a bit complicated, but it really isn't. As you should already know, one can access data arrays in C in many ways. The double asterisk ('**') tells you and the compiler that the variable in question must be a pointer to another pointer. Simple, huh? :) So, when it is later referred to with brackets or double brackets, the compiler knows that it is legal to do so.

No comments: