C Programming Reference

C Programming Reference >> C Basic Programming Tutorials >> 

Arrays And Stringquisite Knowledege 

28/05/07 - 4984 Views - Ratings :   4.17 of 5 / 24 Votes

Level - Beginner
      

Arrays in C is a group of same type of variables refrenced under a common name using a index. String in C on other hand is another name for char array terminated with a null character and has some special properties. Both Arrays and C are stored in continous memmory location and can be combined with pointers to improve code efficiency. Also array can single or multidimension widening the field of situation which they can applied to. C Array and C string find wide application in c programming and forms an integral part of c programming which you should master.

Contents -

1. Single Dimension Array
2. Two Dimensional Array 
3. Multi Dimension Array
4. Passing Array as Parameter 
5. Initalizing Array
6. Variable Length Array
7. Strings
8. Pointers With Array 
9. Pointers With Strings

1. Single Dimension Array

Also known as 1-D array because of its logical representation of 1 Dimension data.

The genral form of declaration of 1-D Array is -

type name [size];
      

Here 'type' is the type of the varibles collected under the common name. 'name' is the common name used to refrence the collected variables. 'size' is the size of the array or the number of variables collected in the array. One important thing is that in this declaration the size should be constant hence making array of this type static with fixed size. This may seem to be a very big restriction on arrays but dynamic variable length arrays can be created in C using dynamic memmory allocation. Also a new feature in C99 lets you create variable length arrays with great ease.

Each element in the array is stored in contiguous memmory location. Total size of array is product of size of the each variable and number of each variable.

Diagram below shows the logical memmory representation of 1-D Array (A - Array Name , X - Array Starting Memmory Location, V - Size of each element in Bits)..

Array 1D Memmory Representation

Elements in array are accessed thorugh an index with valid value 0 to n-1 if n is the size of the array.

One other point to be always kept in mind is that the array boundary can be overrunned since C provides no boundary checking and it is a sole responsibility of the programmer. This is a very dangerous situation because your code is modifying memmory outside of what is allocated to it. You may write into some critical data, Operating System Memmory, Stack etc., which may lead to severe program and O.S. crashes.

Following C Source Code shows how to use a one dimensional array in C.

// Code showing potential use of 1-D Array.



#include <stdio.h>


int main ()
{
   int value [1000],i; // Declaring an Array
   for (i = 0; i<1000; i++)
    {
       value [i] = i; // Loading the Array
    }
   for (i = 0; i<1000; i++)
    {
       printf ("\n%d",value [i]); // Displaying the Array
    }
   return 0; 
}

 

Back To Top

2. Two Dimesion Array

Next in complexity to one dimensional array is Two dimensional array, also known as 2-D array. In simplest terms two dimensional array is an array of one dimensional arrays.

The genral form of declaration of 2-D Array is -

type name [size1] [size2];
      

Here' size1' is the number of 1-D Arrays and 'size2' is the size of each of that 1-D Array.

2-D arrays can be mentally represented as a matrix with 'size1' number of rows and 'size2' number of columns. This can be shown in the figure below -

Array 2D

Total size of the 2-D array = size1 * size2 * size of each variable.

In 2-D array also the index begins with 0 for both parameters. Row value can have possible values 0 to size1 - 1 and columns can have possible values from 0 to size2 - 1.

C Source code below shows the declaration and input/output operations on a 2-D array.

// Code showing potential use of 2-D Array.



#include <stdio.h>

int main ()
{
   int value [100] [100],i,j; // Declaring an Array
   
  for (j = 0; j<100; j++)
   {
   for (i = 0; i<100; i++)
    {
       value [j] [i] = j*100+i; // Loading the Array
    }
   }
  
  for (j = 0; j<100; j++)
  {  
   for (i = 0; i<100; i++)
    {
       printf ("\n%d",value [j] [i]); // Displaying the Array
    }
  }
  return 0; 
}
Back To Top

3. Multi Dimension Array

C Programming language allows more than 2-D array where most of other languages of its class doesnot showing that C is designed to allow scope fot infinite applications.

The general form of declaration of Multidimension array are -

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

The array of type above is called X-D array.

Size of this X-D array = size1 * size2 * size3 * ... * sizeX * size of each variable.

Though allowed array of greater dimension than 3-D is not used because size of the array increases exponentially as dimension increases. Also time to access array indexes increases decreasing the programs efficiency.

Following diagram shows logical memmory representation of a 3-D array as array of 2-D arrays -

Array_3D

C Source Code below shows the declaration and input/output operations on a 3-D array.

// Code showing potential use of 3-D Array.



#include <stdio.h>


int main ()
{
   int value [10] [10] [10] ,i,j,k; // Declaring an Array
   
 for (k = 0; k<10; k++)
 { 
 for (j = 0; j<10; j++)
   {
   for (i = 0; i<10; i++)
    {
       value [k] [j] [i] = k*10+j*10+i; // Loading the Array
    }
   }
 } 
 
 for (k = 0; k<10; k++)
 { 
  for (int j = 0; j<100; j++)
   {  
    for (int i = 0; i<100; i++)
     {
        printf ("\n%d",value [k] [j] [i]); // Displaying the Array
     }
   }
 }
 return 0; 
}

 

Back To Top

4. Passing Array as Parameter

In C entire array cannot be passed as parameter to function entirely. Instead only the base address of the pointer is passed as an argument. This leads to restriction that arrays can be passed only by call by refrence method unlike any other variables which can be passed both by call by refrence and call by value. This restriction can be easily overcomed by declaring passed argument as constant pointer making the function unable to modify the parameter passed simulating call by value to certain extent.

General form passing array as parameter is -

return_type function_name (name [size1] [size2] .... [sizeX]);

Also the left most size (size1) is optional because compiler can calculate its value from the size of array but rest of the sizes are neccesary so another genral form is -

return_type function_name (name [ ] [size2] .... [sizeX]);

C source code below shows the passing of a 1-D, 2-D and 3-D array as parameter to functions.

// Code showing passing of 1-D, 2-D & 3-D Array as parameter.


#include <stdio.h>

void input1D (int data [1000]);
void input2D (int data [100][100]);
void input3D (int data [10][10][10]);
void display1D (int data []);
void display2D (int data [][100]);
void display3D (int data [][10][10]);

int main ()
{
 int array1D [1000];
 int array2D [100] [100];
 int array3D [10] [10] [10];

// Passing Array By First Form
 void input1D (int array1D []);
 void input2D (int array2D [][100]);
 void input3D (int array3D [][10][10]);

// Passing Array By Second Form
 void display1D (int display1D []);
 void display2D (int display2D [][100]);
 void display3D (int display3D [][10][10]);

 return 0;
}

void input1D (int data [1000])
{

 int value [1000],i; // Declaring an Array
   for (i = 0; i<1000; i++)
    {
       value [i] = i; // Loading the Array
    }

}

void input2D (int data [100][100])
{
 int value [100] [100],i,j; // Declaring an Array
   
  for (j = 0; j<100; j++)
   {
   for (i = 0; i<100; i++)
    {
       value [j] [i] = j*10+i; // Loading the Array
    }
   }
}

void input3D (int data [10][10][10])
{
    
 int value [10] [10] [10] ,i,j,k; // Declaring an Array
  for (k = 0; k<10; k++)
   { 
    for (j = 0; j<10; j++)
     {
      for (i = 0; i<10; i++)
       {
        value [k] [j] [i] = k*10+j*10+i; // Loading the Array
       }c
    }
  } 
}

void display1D (int data [])
{
 int value [1000],i;
  for (i = 0; i<1000; i++)
    {
       value [i] = i; // Loading the Array
    }
}

void display2D (int data [][100])
{
 int value [100] [100],i,j
 for (j = 0; j<100; j++)
  {  
   for (i = 0; i<100; i++)
    {
       printf ("\n%d",value [j] [i]); // Displaying the Array
    }
  }

}

void display3D (int data [][10][10])
{
 int value [10] [10] [10] ,i,j,k;
 for (k = 0; k<10; k++)
 { 
  for (int j = 0; j<100; j++)
   {  
    for (int i = 0; i<100; i++)
     {
        printf ("\n%d",value [k] [j] [i]); // Displaying the Array
     }
   }
 }

}

Back To Top

5. Initializing Array

Values in array can be initialize at the time of thier declaration. This is important because they may contain garbage value if not initalized properly and thier usage may be dangerous. Some compilers make sure that unintialized values be 0 or NULL.

The general form of array initalization is -

type name [size1] [size2] .... [sizeX] = { values};

values is a comma seprated list of constants or variables (allowed only in C99), which in case of multi dimensional array is in subaggregated form.

If array is half or partially intialized the rest of the values are automatically changed to zero or NULL.

C Source code below shows the intialization of an 1-D and 2-D array.

// Code showing initializtion of 1-D and 2-D  Array.



#include <stdio.h>


int main ()
{
   int array1D [10], array2D [2] [5], i,j; // Declaring an Array
   
   array1D = {0,1,2,3,4,5,6,7,8,9}; // Intialization of 1D Array
   array2D = {                      // Intializtion of 2D Array
               {1,1},
               {2,2},
               {3,3},
               {4,4},
               {5,5},
             };
   
   for (i = 0; i<10; i++)
    {
       printf ("\n%d",array1D [i]); // Displaying the Array
    }
 
   for (j=0; j<2; j++)
    {  
     for (i = 0; i<5; i++)
      {
        printf ("\n%d",array2D [j] [i]); // Displaying the Array
      }
   } 
  return 0; 
}

One thing that can be noted is that during intialisation that left most index is optional ( that means all index in 1-D Array). This is because the compiler automatically set its value to the minmum value of the size required to store all the initialization safely. This feature provides a innate advantage of overcoming the human error of wrong index value calculation. Now we re-write the C Source Code above to show the C feature of unsized array intialization.

The general form of unsized array initalization is -

type name (name [] [size2] .... [sizeX]) = { values};

// Code showing unisized array initializtion of 1-D and 2-D  Array.



#include <stdio.h>


int main ()
{
   int i,j; 
   
   int array1D []  = {0,1,2,3,4,5,6,7,8,9}; // Unsized Array Intialization of 1D Array
   int array2D [][2] = {                    // Unsized Array Intialization of 2D Array
                        {1,1},
                        {2,2},
                        {3,3},
                        {4,4},
                        {5,5},
                       };
   
   for (i = 0; i<10; i++)
    {
       printf ("\n%d",array1D [i]); 
    }
 
   for (j=0; j<2; j++)
    {  
     for (i = 0; i<5; i++)
      {
        printf ("\n%d",array2D [j] [i]);
      }
   } 
  return 0; 
}

 

Back To Top

 

6. Variable Length Array

As discussed above the size of the array has to be constant otherwise program wont compile. This imposes a severe instruction on the array because its size is limited at compile time. As a result the array formed is static who's size cannot be niether decreased nor increased, this is often against what is required because in many programs size of the array required is known only at run time. For overcoming this restriction we use variable length array whose length can be varied at run time. There are two methods for this and latter one is applicable only in C99.

In first method we use dynamic memmory allocation which will be discussed latter in detail. We take a quick look here how it can solve the problem. We will use malloc function to gets us memory for the array dynamically and the amount of memory fetched is also calculated at run time based on parameter passed to the function. We also use a little use of pointers which is dicussed in details in next tutorial.

C Source Code below shows the potential use of dynamic memory allocation to create variable length array.

#include <stdio.h>
#include <alloc.h>

int * createarray (int length) // This function creates array dynamically on basis of parameter passed and return its base.
{
  int *array;
  array = (int *) malloc (length * size of (int));
  return array; 

}

int main ()
{
    int* array1;
    int* array2;
    array1 = createarray (1000); //Creates array of size 1000.
    array2 = createarray (10000); //Creates array of size 10000.
    return 0; 
}

 

What is achieved above can also be done in a simpler way using a new innovative widely applicable programming construct introduced in C99. This construct is itself called variable length array and is used to create variable length arrays. One important restriction is that they can create only local dynamic array ie. global scope dynamic array is not allowed. They work because they allow a variable to be used as declaring array size whos value is evaluated at runtime.

C Source Code below shows the correct use of C99's variable length array construct to create dynamic arrays.

#include <stdio.h>


void createarray (int length) // This function creates array dynamically on basis of parameter passed using C99 construct.
{
  int array [length];
  for (i = 0; i<length; i++)
    {
       array [i] = i; // Loading the Array
    }
   for (i = 0; i<length; i++)
    {
       printf ("\n%d",array [i]); // Displaying the Array
    }
}

int main ()
{
    createarray (1000); //Creates array of size 1000.
    return 0; 
}

 

Back To Top

7. Strings

Now being well equiped with knowledge about arrays, strings should be a piece of cake for you. String in simplest term is a one dimensional array of characters terminated by a null character ( '\n' ). For safe use size of this string should be one greater than the maximum size string going to be stored in this character array. String in C is equvialent to a real world sentence made by combination of various characters including spaces.

The genral form of declaration of String variable is -

char name [size];


Strings are used to store string constant. String constant in C is a series of characters enclosed within a pair of double quotes. Example of a string constant - " I LOVE C !!!!! ".

Strings like other arrays can be initialised in both normal and unsized way.

The general form of string initalization is -

char name [size]  = "value";

The general form of unsized string initalization is -

char name []  = "value";

Also a string variable though can be accesed (Input/Output) character by character using a loop but generally they are not. The reason being that both printf and scanf provides a simple way of string input/ouput using a %s specifier.

You dont have to worry about NULL character because the compiler would automatically place it on the desired position.

Also string manipulation can be done very easily using some predefined functions available in header <string.h>.

C Source code belows shows the general use of Strings.

#include <stdio.h>
#include <string.h>

int main ()
{
    char enter [6] = "Enter";
    char password [] = "Password";
    char input [100] = "None";
    
    while (1)
     {
       printf ("\n%s %s : ",enter,password);
       scanf ("%s", &input);
       if (strcmp (input,"MYPASSWORD")) //Strcmp function returns zero if two string are equal
        {
            printf ("\nIncorrect Password");
        }
       else
        {
            printf ("\nWelcome to the cyber world .......");
            break;
        }
     }
    return 0; 
}

 

Also a 2-D String Variable can be created which can be logically percieved as Array of strings. General form of declaration of Array of string is -

char name [SIZE1] [SIZE2];

Here SIZE1 indicates the number of strings each having a maximum length of SIZE2.

Basic functionality of Arrays of String can be seen in C Source Code Below.

#include <stdio.h>
#include <string.h>

int main ()
{
    char name [5] [100] = { "Jitesh Banga", "Rohit Goyal", "Nalin Diwan", "Mukesh Kumar", "Manish Jain"}
    char input [100] = "None";
    int i;

    while (1)
     {
       
       printf ("\nEnter Name : ");
       scanf ("%s", &input);
       for ( i = 0; i<5; i++)
        {
          if (!strcmp (input, name [i])
            {
              printf ("\nWelcome %s", name [i]);
              break;
            }
         } 
           
       printf ("\nInvalid User, Access Denied");
     }

return 0; 
}

Back To Top

8. Pointers with Array

Arrays and pointers are very intimately connected. Most important point to remeber is that array name without the brackets is the base address of that array or adress of its first (0th) element. This address can be stored in the pointer.

More fading this subtle diffrence is that pointer can also be used with brackets to index array as if it was an array name.

In general access provided by the pointer is faster if pointer arithemtic(which by the way is almost completely diffrent from normal arithemetic)is used for acess.

Formula for accesing I th element in a 1-D array is -

*(pointer_name + I)

Formula for accesing I th row, Jth Column element in a 2-D array is -

*(pointer_name + I * Number_Of_Elements_Per_Row + J)

And so on , formulae becomes more complicated with increase in dimension of the array.

Code below shows how to access a 1-D array using pointers.

// Code showing potential use of pointer in indexing 1-D Array.



#include <stdio.h>


int main ()
{
   int value [1000],i; // Declaring an Array
   int *pointer;
   pointer = value;
   for (i = 0; i<1000; i++)
    {
       *(pointer +i) = i; // Loading the Array
    }
   for (i = 0; i<1000; i++)
    {
       printf ("\n%d",*(pointer + i); // Displaying the Array
    }
   return 0; 
}

Code below shows how to access a 2-D array using pointers.

// Code showing potential use of pointers in indexing 2-D Array.



#include <stdio.h>

int main ()
{
   int value [100] [100],i,j; // Declaring an Array
   int *pointer;
   pointer = value;
   
  for (j = 0; j<100; j++)
   {
   for (i = 0; i<100; i++)
    {
       *(pointer + i * 100+ j) = j*100+i; // Loading the Array
    }
   }
  
  for (j = 0; j<100; j++)
  {  
   for (i = 0; i<100; i++)
    {
       printf ("\n%d",*(pointer + i * 100+ j)); // Displaying the Array
    }
  }
  return 0; 
}

 

Back To Top

9. Pointers With Strings

As mention above the strings which are innately character array also posses a close relationship with the pointers. It goes one more step ahead than arrays because, the c allow you to assign any arbitary length string constant to char pointer. Memmory allocated in this way is dynamic and compiler uses a table calles string table to store them. Memmory provided to this string table is via heap.

Code belows show the relations between strings and pointer.

#include <stdio.h>
#include <string.h>

int main ()
{
    
   char* mystring;
   char* yourstring;

   mystring = "Hi";
   
   printf ("\nEnter your string : ");
   scanf ("%s", yourstring);
   
   printf ("\nMy string is %s",mystring); //Prints Hi.
   printf ("\nYour string is %s",yourstring);
   
 
   mystring[1] = 'o';

   printf ("\nModified My string is %s",mystring); //Prints Ho.
   
    return 0; 
}

 

Back To Top

 

Reader Comments -

Author Comments
Add Comments 


Name :    
Reply :   


Rating :

Code :
Code

 

 
© 2006 cencyclopedia.com