You are on page 1of 12

This article is part of our on-going C programming series.

There are times while writing C code, you may want to store multiple items of sa me type as contiguous bytes in memory so that searching and sorting of items bec omes easy. For example: Storing a string that contains series of characters. Like storing a name in memo ry. Storing multiple strings. Like storing multiple names. C programming language provides the concept of arrays to help you with these sce narios. 1. What is an Array? An array is a collection of same type of elements which are sheltered under a co mmon name. An array can be visualised as a row in a table, whose each successive block can be thought of as memory bytes containing one element. Look at the figure below : An Array of four elements: +===================================================+ | elem1 | elem2 | elem3 | elem4 | +===================================================+ The number of 8 bit bytes that each element occupies depends on the type of arra y. If type of array is char then it means the array stores character elements. Sin ce each character occupies one byte so elements of a character array occupy one byte each.

2. How to Define an Array? An array is defined as following : <type-of-array> <name-of-array> [<number of elements in array>]; type-of-array: It is the type of elements that an array stores. If array stores character elements then type of array is char . If array stores integer elements th en type of array is int . Besides these native types, if type of elements in array is structure objects then type of array becomes the structure. name-of-array: This is the name that is given to array. It can be any string but it is usually suggested that some can of standard should be followed while nami ng arrays. At least the name should be in context with what is being stored in t he array. [number of elements]: This value in subscripts [] indicates the number of elemen ts the array stores. For example, an array of five characters can be defined as : char arr[5]; 3. How to Initialize an Array? An array can be initialized in many ways as shown in the code-snippets below. Initializing each element separately. For example : int arr[10]; int i = 0; for(i=0;i<sizeof(arr);i++) {

arr[i] = i; // Initializing each element seperately } Initializing array at the time of declaration. For example : int arr[] = {'1','2','3','4','5'}; In the above example an array of five integers is declared. Note that since we a re initializing at the time of declaration so there is no need to mention any va lue in the subscripts []. The size will automatically be calculated from the num ber of values. In this case, the size will be 5. Initializing array with a string (Method 1): Strings in C language are nothing but a series of characters followed by a null byte. So to store a string, we need an array of characters followed by a null by te. This makes the initialization of strings a bit different. Let us take a look : Since strings are nothing but a series of characters so the array containing a s tring will be containing characters char arr[] = {'c','o','d','e','\0'}; In the above declaration/initialization, we have initialized array with a series of character followed by a \0' (null) byte. The null byte is required as a termi nating byte when string is read as a whole. Initializing array with a string (Method 2): char arr[] = "code"; Here we neither require to explicitly wrap single quotes around each character n or write a null character. The double quotes do the trick for us. 4. Accessing Values in an Array Now we know how to declare and initialize an array. Lets understand, how to acce ss array elements. An array element is accessed as : int arr[10]; int i = 0; for(i=0;i<sizeof(arr);i++) { arr[i] = i; // Initializing each element separately } int j = arr[5]; // Accessing the 6th element of integer array arr and assigning its value to integer 'j'. As we can see above, the 6th element of array is accessed as arr[5] . Note that for an array declared as int arr[5]. The five values are represented a s: arr[0] arr[1] arr[2] arr[3] arr[4] and not arr[1] arr[2] arr[3] arr[4] arr[5] The first element of array always has a subscript of 0' 5. Array of Structures The following program gives a brief idea of how to declare, initialize and use a rray of structures. #include<stdio.h> struct st{ int a;

char c; }; int main() { struct st st_arr[3]; // Declare an array of 3 structure objects struct st st_obj0; // first structure object st_obj0.a = 0; st_obj0.c = 'a'; struct st st_obj1; //Second structure object st_obj1.a = 1; st_obj1.c = 'b'; struct st st_obj2; // Third structure object st_obj2.a = 2; st_obj2.c = 'c'; st_arr[0] = st_obj0; // Initializing first element of array with first struc ture object st_arr[1] = st_obj1; // Initializing second element of array with second str ucture object st_arr[2] = st_obj2; // Initializing third element of array with third struc ture object printf("\n First Element of array has values of a = [%d] and c = [%c]\n", st _arr[0].a, st_arr[0].c); printf("\n Second Element of array has values of a = [%d] and c = [%c]\n", s t_arr[1].a, st_arr[1].c); printf("\n Third Element of array has values of a = [%d] and c = [%c]\n", st _arr[2].a, st_arr[2].c); return 0; } The output of the above program comes out to be : $ ./strucarr First Element of array has values of a = [0] and c = [a] Second Element of array has values of a = [1] and c = [b] Third Element of array has values of a = [2] and c = [c] 6. Array of Char Pointers The following program gives a brief Idea of how to declare an array of char poin ters : #include<stdio.h> int main() { // Declaring/Initializing three characters pointers char *ptr1 = "Himanshu"; char *ptr2 = "Arora"; char *ptr3 = "TheGeekStuff"; //Declaring an array of 3 char pointers char* arr[3];

// Initializing the array with values arr[0] = ptr1; arr[1] = ptr2; arr[2] = ptr3; //Printing printf("\n printf("\n printf("\n the values stored in array [%s]\n", arr[0]); [%s]\n", arr[1]); [%s]\n", arr[2]);

return 0; } The output of the above program is : $ ./charptrarr [Himanshu] [Arora] [TheGeekStuff] 7. Pointer to Arrays Pointers in C Programming language is very powerful. Combining pointers with arr ays can be very helpful in certain situations. As to any kind of data type, we can have pointers to arrays also. A pointer to a rray is declared as : <data type> (*<name of ptr>)[<an integer>] For example : int(*ptr)[5]; The above example declares a pointer ptr to an array of 5 integers. Lets look at a small program for demonstrating this : #include<stdio.h> int main(void) { char arr[3]; char(*ptr)[3]; arr[0] = 'a'; arr[1] = 'b'; arr[2] = 'c'; ptr = &arr; return 0; } In the above program, we declared and initialized an array arr and then declared a pointer ptr to an array of 3 characters. Then we initialized ptr with the address of array arr . 8. Static vs Dynamic Arrays Static arrays are the ones that reside on stack. Like :

char arr[10]; Dynamic arrays is a popular name given to a series of bytes allocated on heap. t his is achieved through malloc() function. Like : char *ptr = (char*)malloc(10); The above line allocates a memory of 10 bytes on heap and we have taken the star ting address of this series of bytes in a character pointer ptr. Static arrays are used when we know the amount of bytes in array at compile time while the dynamic array is used where we come to know about the size on run tim e. 9. Decomposing Array into Pointers Internally, arrays aren t treated specially, they are decomposed into pointers and operated there-on. For example an array like : char arr[10]; When accessed like : arr[4] = 'e'; is decomposed as : *(arr + 4) = 'e' So we see above that the same old pointers techniques are used while accessing a rray elements. 10. Character Arrays and Strings Mostly new programmers get confused between character arrays and strings. Well, there is a very thin line between the two. This thin line only comprises of a nu ll character \0' . If this is present after a series of characters in an array, t hen that array becomes a string. This is an array: char arr[] = {'a', 'b', 'c'}; This is a string: char arr[] = {'a', 'b', 'c', '\0'}; Note : A string can be printed through %s format specifier in printf() while an printing an array through %s specifier in printf() is a wrong practice. 11. Bi-dimensional and Multi-dimensional Arrays The type of array we discussed until now is single dimensional arrays. As we see earlier, we can store a set of characters or a string in a single dimensional a rray. What if we want to store multiple strings in an array. Well, that wont be possible using single dimensional arrays. We need to use bi-dimensional arrays i n this case. Something like : char arr[5][10]; The above declaration can be thought of as 5 rows and 10 columns. Where each row may contain a different name and columns may limit the number of characters in the name. So we can store 5 different names with max length of 10 characters eac h. Similarly, what if we want to store different names and their corresponding addr esses also. Well this requirement cannot be catered even by bi-dimensional array s. In this case we need tri-dimensional (or multi-dimensional in general) arrays . So we need something like :

char arr[5][10][50]; So we can have 5 names with max capacity of 10 characters for names and 50 chara cters for corresponding addresses. Since this is an advanced topic, So we won t go into practical details here. 12. A Simple C Program using Arrays Consider this simple program that copies a string into an array and then changes one of its characters : #include<stdio.h> #include<string.h> int main(void) { char arr[4];// for accommodating 3 characters and one null '\0' byte. char *ptr = "abc"; //a string containing 'a', 'b', 'c', '\0' memset(arr, '\0', sizeof(arr)); //reset all the bytes so that none of the by te contains any junk value strncpy(arr,ptr,sizeof("abc")); // Copy the string "abc" into the array arr printf("\n %s \n",arr); //print the array as string arr[0] = 'p'; // change the first character in the array printf("\n %s \n",arr);//again print the array as string return 0; } I think the program is self explanatory as I have added plenty of comments. The output of the above program is : $ ./array_pointer abc pbc So we see that we successfully copied the string into array and then changed the first character in the array. 13. No Array Bound Check in a C Program What is array bound check? Well this is the check for boundaries of array declar ed. For example : char arr[5]; The above array bytes using : arr consumes 5 bytes on stack and through code we can access these

arr[0], arr[1], arr[2], arr[3], arr[4] Now, C provides open power to the programmer to write any index value in [] of a n array. This is where we say that no array bound check is there in C. SO, misus ing this power, we can access arr[-1] and also arr[6] or any other illegal locat ion. Since these bytes are on stack, so by doing this we end up messing with oth er variables on stack. Consider the following example : #include<stdio.h> unsigned int count = 1;

int main(void) { int b = 10; int a[3]; a[0] = 1; a[1] = 2; a[2] = 3; printf("\n b = %d \n",b); a[3] = 12; printf("\n b = %d \n",b); return 0; } In the above example, we have declared an array of 3 integers but try to access the location arr[3] (which is illegal but doable in C) and change the value kept there. But, we end up messing with the value of variable b . Cant believe it?, check the f ollowing output . We see that value of b changes from 10 to 12. $ ./stk b = 10 b = 12 What is an Array in C Language? An array in C Programing Language can be defined as number of memory locations, each of which can store the same data type and which can be references through t he same variable name. An array is a collective name given to a group of similar quantities. These simi lar quantities could be percentage marks of 100 students, number of chairs in ho me, or salaries of 300 employees or ages of 25 students. Thus an array is a coll ection of similar elements. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a string , where as an array of integers or floats is called simply an array. All elements of any given array must be of the same type i.e we can t have an array of 10 numb ers, of which 5 are ints and 5 are floats. Arrays and pointers have a special relationship as arrays use pointers to refere nce memory locations. Declaration of an Array Arrays must be declared before they can be used in the program. Standard array d eclaration is as type variable_name[lengthofarray]; Here type specifies the variable type of the element which is going to be stored in the array. In C programmin language we can declare the array of any basic st andard type which C language supports. For example double height[10]; float width[20]; int min[9]; char name[20]; In C Language, arrays starts at position 0. The elements of the array occupy adj acent locations in memory. C Language treats the name of the array as if it were a pointer to the first element This is important in understanding how to do ari

thmetic with arrays. Any item in the array can be accessed through its index, an d it can be accesed any where from with in the program. So m=height[0]; variable m will have the value of first item of array height. The program below will declare an array of five integers and print all the eleme nts of the array. int myArray [5] = {1,2,3,4,5}; /* To print all the elements of the array for (int i=0;i<5;i++){ printf("%d", myArray[i]); } Initializing Arrays Initializing of array is very simple in c programming. The initializing values a re enclosed within the curly braces in the declaration and placed following an e qual sign after the array name. Here is an example which declares and initialize s an array of five elements of type int. Array can also be initialized after dec laration. Look at the following C code which demonstrate the declaration and ini tialization of an array. int myArray[5] = {1, 2, 3, 4, 5}; //declare and initialize the array in one stat ement int studentAge[4]; studentAge[0]=14; studentAge[1]=13; studentAge[2]=15; studentAge[3]=16; Performing operations on Arrays Here is a program that will demonstrate the simple operations of the array. #include <stdio.h> void oneWay(void); void anotherWay(void); int main(void) { printf("\noneWay:\n"); oneWay(); printf("\nantherWay:\n"); anotherWay(); } /*Array initialized with aggregate */ void oneWay(void) { int vect[10] = {1,2,3,4,5,6,7,8,9,0}; int i; for (i=0; i<10; i++){ printf("i = %2d vect[i] = %2d\n", i, vect[i]); } } /*Array initialized with loop */ void anotherWay(void) { int vect[10]; int i; for (i=0; i<10; i++) vect[i] = i+1; for (i=0; i<10; i++) printf("i = %2d vect[i] = %2d\n", i, vect[i]); }

/* The output of oneWay: i = 0 vect[i] i = 1 vect[i] i = 2 vect[i] i = 3 vect[i] i = 4 vect[i] i = 5 vect[i] i = 6 vect[i] i = 7 vect[i] i = 8 vect[i] i = 9 vect[i]

this program is = = = = = = = = = = 1 2 3 4 5 6 7 8 9 0

antherWay: i = 0 vect[i] = 1 i = 1 vect[i] = 2 i = 2 vect[i] = 3 i = 3 vect[i] = 4 i = 4 vect[i] = 5 i = 5 vect[i] = 6 i = 6 vect[i] = 7 i = 7 vect[i] = 8 i = 8 vect[i] = 9 i = 9 vect[i] = 10 */ Here is a more complex program that will demonstrate how to read, write and trav erse the integer arrays #include <stdio.h> void intSwap(int *x, int *y); int getIntArray(int a[], int nmax, int sentinel); void printIntArray(int a[], int n); void reverseIntArray(int a[], int n); int main(void) { int x[10]; int hmny; hmny = getIntArray(x, 10, 0); printf("The array was: \n"); printIntArray(x,hmny); reverseIntArray(x,hmny); printf("after reverse it is:\n"); printIntArray(x,hmny); } void intSwap(int *x, int *y) /* It swaps the content of x and y */ { int temp = *x; *x = *y; *y = temp; } /* n is the number of elements in the array a. * These values are printed out, five per line. */ void printIntArray(int a[], int n){ int i; for (i=0; i<n; ){

printf("\t%d ", a[i++]); if (i%5==0) printf("\n"); } printf("\n"); } /* It reads up to nmax integers and stores then in a; sentinel * terminates input. */ int getIntArray(int a[], int nmax, int sentinel) { int n = 0; int temp; do { printf("Enter integer [%d to terminate] : ", sentinel); scanf("%d", &temp); if (temp==sentinel) break; if (n==nmax) printf("array is full\n"); else a[n++] = temp; }while (1); return n; } /* It reverse the order of the first n elements of array */ void reverseIntArray(int a[], int n) { int i; for(i=0;i<n/2;i++){ intSwap(&a[i],&a[n-i-1]); } } Copy one array into another There is no such statement in C language which can directly copy an array into a nother array. So we have to copy each item seperately into another array. #include <stdio.h> int main() { int iMarks[4]; short newMarks[4]; iMarks[0]=78; iMarks[1]=64; iMarks[2]=66; iMarks[3]=74; for(i=0; i<4; i++) newMarks[i]=iMarks[i]; for(j=0; j<4; j++) printf("%d\n", newMarks[j]); return 0; } To summarize, arrays are provides a simple mechanism where more than one element s of same type are to be used. We can maintain, manipulate and store multiple el ements of same type in one array variable and access them through index. Multidimensional Arrays In C Language one can have arrays of any dimensions. To understand the concept

of multidimensional arrays let us consider the following 4 X 5 matrix Row number (i) Column 0 11 3 1 5 6 2 -8 9 3 10 13 Let us assume the name numbers (j) 5 -9 -8 7 2 12 -10 4 of matrix is x -6 24 45 5

To access a particular element from the array we have to use two subscripts on f or row number and other for column number the notation is of the form X [i] [j] where i stands for row subscripts and j stands for column subscripts. Thus X [0] [0] refers to 10, X [2] [1] refers to 16 and so on In short multi dimensional a rrays are defined more or less in the same manner as single dimensional arrays, except that for subscripts you require two squire two square brackets. We will r estrict our decision to two dimensional arrays. Below given are some typical two-dimensional array definitions float table [50] [50]; char line [24] [40]; The first example defines tables as a floating point array having 50 rows and 50 columns. the number of elements will be 2500 (50 X50). The second declaration example establishes an array line of type character with 24 rows and 40 columns. The number of elements will be (24 X 40) 1920 consider t he following two dimensional array definition int values [3] [4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10. 11, 12, }; Values [0] [0] = 1 Values [0] [1] = 2 Values [0] [2] = 3 Values [0] [3] = 4 Values [1] [0] = 5 Values [1] [1] = 6 Values [1] [2] = 7 Values [1] [3] = 8 Values [2] [0] = 9 Values [2] [1] = 10 Values [2] [2] = 11 Values [2] [3] = 12 Here the first subscript stands for the row number and second one for column num ber. First subscript ranges from 0 to 2 and there are altogether 3 rows second o ne ranges from 0 to 3 and there are altogether 4 columns. Alternatively the above definition can be defined and initialised as int values [3] [4] = { { 1, 2, 3, 4 } { 5, 6, 7, 8 } { 9, 10, 11, 12 } }; Here the values in first pair of braces are initialised to elements of first row , the values of second pair of inner braces are assigned to second row and so on . Note that outer pair of curly braces is required. If there are two few values within a pair of braces the remaining elements will be assigned as zeros. Here is a sample program that stores roll numbers and marks obtained by a studen t side by side in matrix main ( ) { int stud [4] [2];

int i, j; for (i =0; i < =3; i ++) { printf ("\n Enter roll no. and marks"); scanf ("%d%d", &stud [i] [0], &stud [i] [1] ); } for (i = 0; i < = 3; i ++) printf ("\n %d %d", stud [i] [0], stud [i] [1]); }

You might also like