Monday, March 25, 2013

Array in c prograqmmming




There are times while writing C code, you may want to store multiple items of same type as contiguous bytes in memory so that searching and sorting of items becomes easy. For example:
  1. Storing a string that contains series of characters. Like storing a name in memory.
  2. Storing multiple strings. Like storing multiple names.
C programming language provides the concept of arrays to help you with these scenarios.




1. What is an Array?

An array is a collection of same type of elements which are sheltered under a common 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 array. If type of array is ‘char’ then it means the array stores character elements. Since 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 then 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 naming arrays. At least the name should be in context with what is being stored in the array.
  • [number of elements]: This value in subscripts [] indicates the number of elements 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 are initializing at the time of declaration so there is no need to mention any value in the subscripts []. The size will automatically be calculated from the number 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 byte. 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 string 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 terminating 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 nor 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 access 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 5th element of integer array arr and assigning its value to integer 'j'.
As we can see above, the 5th element of array is accessed as ‘arr[5]‘.
Note that for an array declared as int arr[5]. The five values are represented as: 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 array 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 structure object
    st_arr[1] = st_obj1; // Initializing second element of array with second structure object
    st_arr[2] = st_obj2; // Initializing third element of array with third structure 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", st_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 pointers :
#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 the values stored in array
    printf("\n [%s]\n", arr[0]);
    printf("\n [%s]\n", arr[1]);
    printf("\n [%s]\n", arr[2]); 
 
    return 0;
}
The output of the above program is :
$ ./charptrarr 
 
 [Himanshu] 
 
 [Arora] 
 
 [TheGeekStuff]

No comments:

Post a Comment