home
C TUTORIALS

ARRAYS

An array is a sequenced collection of related data items that share a commom name.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

first element
last element
Element[0] Element[1] Element[2] -------- Element[n]


There are following few important concepts related to array which should be clear to a C programmer:

Types of arrays:




One-dimensional arrays


Like any other variable, arrays must be declared before they are used so that the compiler can allocate space for them in memory. The general form of array declaration is
type variable-name[size];

This is called a single-dimensional array. The size must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 9-element array called height of type float, use this statement:
float height[9];

Now balance is avariable array which is sufficient to hold upto 10 double numbers.

Initializing Arrays


After an array is declared, its elements must be initialised. Otherwise, they will contain "garbage". An array can be initialised at either of the following stages:


Compile Time Initialization
The general form of initialization of arrays is:

type array-name[size]={list of values};


For example,
float total[5]={0.0,15.75,-10};


will initialise the first three element to 0.0,15.75,-10 and the remaining two elements to zero.
The size can be omitted. In such case, the compiler allocates enough space for all initialized elements.
Character arrays may be initialized in a similar manner.For example,

char name[]={'R','A','M','/0'};


declares the name to be an array of four characters,initialized with the string "RAM" ending with null character. We call also asign the string as:

char name[]="RAM";



Run Time Initialization
An array can be explicitly initialised at run time. We read the function such as scanf to initalize an array.For example,

int x[3];
scanf("%d%d%d",&x[0],&x[1],&x[2]);


will initialize array elements with the values entered through keyboard.


For example:

#include < stdio.h> int main () { int n[ 10 ]; /* n is an array of 10 integers */ int i; /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) { scanf("%d",&n[i]); /* reading the elements */ } /* output each array element's value */ for (i= 0; i < 10; i++ ) { printf("n[%d] = %d\n", i, n[i] ); } return 0; }

Two-dimensional arrays


The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y you would write something as follows:
type arrayName [ x ][ y ];

Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array can be think as a table which will have x number of rows and y number of columns. A 2-dimensional array a, which contains two rows and three columns can be shown as below:

column0 column1 column2
row0 a[0][0]; a[0][1]; a[0][2];
row1 a[1][0]; a[1][1]; a[1][2];



Thus, every element in array a is identified by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.

Initializing Two-Dimensional Arrays:



Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.

int a[2][3] = { {0, 1, 2} , /* initializers for row indexed by 0 */ {3, 4, 5} , /* initializers for row indexed by 1 */ };


The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example:

int a[2][3] = {0,1,2,3,4,5};


Accessing Two-Dimensional Array Elements:


An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example:

int val = a[2][3];


The above statement will take 4th element from the 3rd row of the array. You can verify it in the above diagram. Let us find the transpose of two N*N matrices:

#include < stdio.h> int main () { int i,j,a[3][3],b[3][3]; printf("Enter a 3*3 matrix:\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("a[%d][%d]=",i,j); scanf("%d",&a[i][j]); } } printf("\nThe entered matrix is:\n"); for(i=0;i<3;i++) { printf("\n"); for(j=0;j<3;j++) { printf("%d\t",a[i][j]); } } for(i=0;i<3;i++) { for(j=0;j<3;j++) b[i][j]=a[j][i]; \*to find transpose of the matrix*\ } printf("\n\nThe transpose of the matrix is:\n"); for(i=0;i<3;i++) { printf("\n"); for(j=0;j<3;j++) { printf("%d\t",b[i][j]); } } getch(); }



The output is:

enter a 3*3 matrix: a[0][0]=1; a[0][1]=2; a[0][2]=3; a[1][0]=4; a[1][1]=5; a[1][2]=6; a[2][0]=7; a[2][1]=8; a[2][2]=9; The entered matrix is: 1 2 3 4 5 6 7 8 9 The transpose of the matrix is: 1 4 7 2 5 8 3 6 9


As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.


Multi-dimensional arrays


C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration:

type name[size1][size2]...[sizeN];


For example, the following declaration creates a three dimensional 5, 10, 4 integer array:

int threedim[5][10][4];



Passing array to function


Array elements can be passed to a function by calling the function by value, or by reference. In the call by value we pass values of array elements to the function, whereas in the call by reference we pass addresses of array elements to the function.

/*Demonstration of call by value*/ main() { int i; int marks[]={5,6,7,8,9}; for(i=0;i<=6;i++) display(marks[i]); } display(int m) { printf("%d",m); }


The output is:

5,6,7,8,9


Note that since at a time only one element is being passed, this element is collected in an ordinary integer variable m, in the function display().


And now the call by reference.

/*Demonstration of call by reference*/ main() { int i; int marks[]={5,6,7,8,9}; for(i=0;i<=6;i++) display(&marks[i]); } display(int *m) { printf("%d",*m); }
The output is:

5,6,7,8,9


Here we are passing addresses of individual array elements to the function display().
The variable in which this address is collected(m) is declared as a pointer variable. And since m contains the address of array element, to print out the array element we are using the 'value at address' operator(*).


Pointers and array


Assuming you have bit understanding on pointers in C programming language, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration:

double balance[50];


balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p the address of the first element of balance:

double *p; double balance[10]; p = balance;


It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].

Once you store the address of first element in p, you can access array elements using *p, *(p+1), *(p+2) and so on. Below is the example to show all the concepts discussed above:

#include < stdio.h> int main () { /* an array with 5 elements */ double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; double *p; int i; p = balance; /* output each array element's value */ printf( "Array values using pointer\n"); for ( i = 0; i < 5; i++ ) { printf("*(p + %d) : %f\n", i, *(p + i) ); } printf( "Array values using balance as address\n"); for ( i = 0; i < 5; i++ ) { printf("*(balance + %d) : %f\n", i, *(balance + i) ); } return 0; }


When the above code is compiled and executed, it produces the following result:

Array values using pointer *(p + 0) : 1000.000000 *(p + 1) : 2.000000 *(p + 2) : 3.400000 *(p + 3) : 17.000000 *(p + 4) : 50.000000 Array values using balance as address *(balance + 0) : 1000.000000 *(balance + 1) : 2.000000 *(balance + 2) : 3.400000 *(balance + 3) : 17.000000 *(balance + 4) : 50.000000



In the above example, p is a pointer to double, which means it can store address of a variable of double type. Once we have address in p, then *p will give us value available at the address stored in p, as we have shown in the above example.