Arrays
An array is a collection of variables of the same type. Individual array elements are identified by an integer index. In C the index begins at zero and is always written inside square brackets.
We have already met single dimensioned arrays which are declared like this
int results[20];
Arrays can have more dimensions, in which case they might be declared as
int results_2d[20][5];
int results_3d[20][5][3];
Each index has its own set of square brackets. An array is declared in the main function, usually has details of dimensions included. It is possible to use another type called a pointer in place of an array. This means that dimensions are not fixed immediately, but space can be allocated as required. This is an advanced technique which is only required in certain specialized programs.
As an example, here is a simple function to add up all of the integers in a single dimensioned array.
int add_array(int array[], int size)
{
int i;
int total = 0;
for(i = 0; i < size; i++)
total += array[i];
return(total);
}
The program given next will make a string, access some data in it, print it out. Access it again using pointers, and then print the string out. It should print “Hi!” and “012345678” on different lines. Let us see the coding of the program:
#include <stdio.h>
#define STR_LENGTH 10
void main()
{
char Str[STR_LENGTH];
char* pStr;
int i;
Str[0] = 'H';
Str[1] = 'i';
Str[2] = '!';
Str[3] = '\0'; // special end string character NULL
printf("The string in Str is : %s\n", Str);
pStr = &Str[0];
for (i = 0; i < STR_LENGTH; i++)
{
*pStr = '0'+i;
pStr++;
}
Str[STR_LENGTH-1] = '\0';
printf("The string in Str is : %s\n", Str);
}
[] (square braces) are used to declare the array. The line of the program char Str[STR_LENGTH]; declares an array of ten characters. These are ten individual characters, which are all put together in memory into the same place. They can all be accessed through our variable name Str along with a [n] where n is the element number.
It should always be kept in mind when talking about array that when C declares an array of ten, the elements you can access are numbered 0 to 9. Accessing the first element corresponds to accessing the 0th element. So in case of Arrays always count from 0 to size of array - 1.
Next notice that we put the letters "Hi!" into the array, but then we put in a '\0' you are probably wondering what this is. "\0" stands for NULL and represents the end of string. All character strings need to end with this special character '\0'. If they do not, and then someone calls printf on the string, then printf would start at the memory location of your string, and continue printing tell it encounters '\0' and thus you will end up with a bunch of garbage at the end of your string. So make sure to terminate your strings properly.
|