Basics of C Arrays

C language provides a capability called ‘array’ that enables the user to design a set of similar data types. Very often, one needs to process collections of related data items, such as addition of fifty numbers, test scores of students in a university, a set of measurements resulting from an experiment, income tax tables, etc. One way of handling such a situation would be to declare a new variable name for each of these data items. This approach obviously is quite cumbersome, if not altogether impossible.

A better way to solve the problem is to use an array of a corresponding data type. This enables the user to access any number of relative data type using a single name and subscript.

Definition

An ordered finite collection of data items, each of the same type, is called an array, and the individual data items are its elements. Only one name is assigned to an array and specifying a subscript references individual elements.

A subscript is also called an index. In C, subscripts start at 0, rather than 1, and cannot be negative. The single group name and the subscript are associated by enclosing the subscript in square brackets to the right of the name.

Consider an example where marks of some students are stored in an array named mark, then mark[0] refers to the marks of first student, mark[1] to the marks of second student, mark[10] to the marks of eleventh student and mark[n-1] to the marks of nth student.

An array has the following properties:

  • The type of an array is the data type of its elements.
  • The location of an array is the location of its first element.
  • The length of an array is the number of data elements in the array.
  • The storage required for an array is the length of the array times the size of an element.

Arrays, whose elements are specified by one subscript, are called one-dimensional arrays. Arrays, whose elements are specified by more than one subscript, are called multi-dimensional arrays.

Declartion of single dimension array

Arrays, like simple variables, need to be declared before use. An array declaration is of the form:

data-type arrayname[size] ;

where,
data-type: The type of data stored in the array.
arrayname: Name of the array.
Size: Maximum number of elements that the array can hold.

Hence, an array num of 50 integer elements can be declared as:

Initialization of single dimensional array

Elements of an array can be assigned initial values by following the array definition with a list of initializers enclosed in braces and separated by commas.

For example, the declaration:

int mark[5] = {40,97,91,88,100}; 

declares an array mark to contain five integer elements and initializes the elements of array as given below:

mark[0]   40 
mark[1]   97 
mark[2]   91 
mark[3]   88 
mark[4]   100

The declaration:

char name[3] = {‘R’,’A’,’J’};

declares an array name to contain three character elements and initializes the elements of array as given below:

name[0]     'R'
name[1]     'A' 
name[2]     'J'

The declaration:

float price[7] = {0.25, 15.5, 10.7, 26.8, 8.8, 2.8, 9.7};

declares an array price to contain seven float elements and initializes the elements of array as given below:

price[0]      0.25 
price[1]      15.5 
price[2]      10.7 
price[3]      26.8 
price[4]      8.8 
price[5]      2.8 
price[6]      9.7

Since any constant integral expression may be used to specify the number of elements in an array, symbolic constants or expressions involving symbolic constants may also appear in array declarations.

For example, the declaration:

#define UNIT_PRICE 80 
#defineTOT_PRICE 100 
int sl_price[UNIT_PRICE] ; 
int nt_price[TOT_PRICE] ;

declare sl_price and nt_price to be one-dimensional integer array of 80 and 100 elements respectively. The array size may be omitted during declaration.

Thus, the declaration,

int mark[] = {40,97,91,88,100}; 

is equivalent to:

int mark[5] = {40,97,91,88,100};

In such cases, the subscript is assumed to be equal to the number of elements in the array (5 in this case). The elements, which are not explicitly initialized, are automatically set to zero.

int x[4]={1,2}; implies 
      x[0]=1 
      x[1]=2 
      x[2]=0 
      x[3]=0

Array elemets in memory

Consider the following array declaration:

int num[100];

In the above declaration, 400 bytes get immediately reserved in memory, as each of the 100 integers would be of 4 bytes long. An array is a set of contiguous memory locations, first element starting at index zero. The allocation will be like this.

As seen above, array elements are always numbered (index) from 0 to (n-1) where n is the size of the array.

Array Processing

The capability to represent a collection of related data items by a single array enables the development of concise and efficient programs. An individual array element can be used in a similar manner that a simple variable is used. That is the user can assign a value, display its value or perform arithmetic operations on it.

To access a particular element in an array, specify the array name, followed by square braces enclosing an integer, which is called the Array Index.

For example, The assignment statement,

num[5] = 2 ;

assigns 2 to 6th element of num.

p = (net[1] + amount[9]) /2 ; 

assigns the average value of 2nd element of net and 10th element of amount to p.

The statement

--num[8] ;

decrements the content of the 9th element of num by 1.

The assignment statements,

i = 5; 
p = num[++i] ;

assigns the value of num[6] to p.

whereas the statements,

i = 5 ; 
p = num[i++] ; 

assign the value of num[5] to p.

However, all operations involving entire arrays must be performed on an element-by-element basis. This is done using loops. The number of loop iterations will hence equal the number of array elements to be processed.

As an illustration of the use of arrays, consider the following program.

/* Program to find average marks obtained by 25 students in a test by accepting marks of each student */ 
# include <stdio.h>
void main(void) 
{  
   int i; 
   float sum=0; 
   float mark[25]; 
   for(i=0;i<25;i++) 
   { 
       printf(“Enter marks : “); 
       scanf(“%f”,&mark[i]); 
       sum += mark[i]; 
   } 
   printf(“\n Average marks : %.2f \n”,sum/25); 
}

What are Strings

A string constant is one-dimensional array of characters terminated by a null (‘\0’) character. Strings are used to store text information and to perform manipulations on them. Strings are declared in the same manner as other arrays.

For Example:

char fruit[10];

Initializing Character Arrays

Character arrays can be initialized in two ways as individual characters or as a single string.

char name[ ] = {‘P’, ’a’, ’t’, ’n’, ‘i’, ’\0’}; 

Each character in the array occupies one byte of memory and the last character is always ‘\0’, which is a single character. The null character acts as a string terminator. Hence a string of n elements can hold (n-1) characters.

char fruit[ ] = “Apple”; 

Note that, in this declaration ‘\0’ is not necessary, C inserts the null character automatically, when the array is initialized with a double quoted string constant.

When initializing a character array, the length may be omitted. The compiler automatically allocates the storage depending on the length of the value given.

char name[ ] = "Geek"; 

The above declaration automatically assigns storage equivalent to 6 characters including ‘\0’ to the character array name.

Memory representation of above array is shown below:

G e e k \0
/* Program to accept and print a string */ 
void main(void) 
{ 
    char name[20]; 
    scanf(“%s”, name); 
    printf(“%s”, name); 
}

The %s used in printf() is a format specification for printing out a string. The same specification can be used with scanf() also. In both cases we are supplying the base address to the functions. The scanf() function , after the enter is pressed automatically inserts a ‘\0’ at the end of the string. The scanf() function is not capable of receiving multi-word strings separated by space. In that case use the gets() and puts() functions.

/* Program that accepts and prints a string using gets and puts functions */#include  
#include <stdio.h>
#include <string.h>main() 
{ 
   char name[20]; 
   gets(name); 
   puts(name); 
}
/* Program to compute the length of a given string */#include <stdio.h>
void main(void) 
{ 
   char str[10]; 
   int len; 
   printf("\n Enter string :"); 
   scanf("%[^\n]", arr1); 
   for(len = 0; str[len] != '\0'; len++); 
   printf("\nThe length of the string is %d\n", len); 
}

Passing arrays to functions

Sometimes it’s inconvenient to call a function that requires a long list of arguments. One way around this, is to store your variables into an array, then pass a POINTER to the array to the function. This method will be discussed in greater detail in the pointers section, but for now you need to know that the array isn’t actually passed to the function – just the array’s location in the memory. This is known as PASS BY REFERENCE. The name of an array references the array’s location in the memory, its ADDRESS.

/* Passing Arrays to functions */#include <stdio.h> 
int addNumbers(int fiveNumbers[]); /* declare function */ 
int main() 
{ 
    int array[5]; 
    int i; 
    printf("Enter 5 integers separated by spaces:"); 
    for(i=0 ; i<5 ; i++) 
    { 
       scanf("%d", &array[i]); 
    } 
    printf("\nTheir sum is: %d\n", addNumbers(array)); 
    return 0; 
} 

int addNumbers(int fiveNumbers[]) /* define function */ 
{ 
int sum = 0; 
int i; 
    for(i=0 ; i<5 ; i++) 
    { 
        sum+=fiveNumbers[i]; /* work out the total */ 
    } 
    return sum; /* return the total */ 
}

Notice that the size of the array is blank in both the function declaration and definition – the compiler works it out for you. Also, when the function is called, the name of the array is passed. This is the equivalent to passing &array[0] – the address of the first element.

Multidimensional Arrays

This is similar to passing 1D array but, in the function declarations you must specify all the dimension sizes (only the leftmost one is optional).

/* Passing Multi dimensional Arrays to functions */#include <stdio.h>   
void printArray(int array[][4]); /* declare function */ 

int main() 
{ 
   int array[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11}; 
   printArray(array); 
   return 0; 
}

void printArray(int array[][4]) 
{ 
   /* define function */ 
   int i, j; 
   for(i=0 ; i<3 ; i++) 
   { 
      for(j=0 ; j<4 ; j++) { 
         printf("%2d ", array[i][j]); 
      printf(“\n”); 
    } 
    printf("\n"); 
    } 
}

Passing Strings to Functions

To pass addresses to a function (referred to as pass by reference), you can use the array name. If your function needs to know how many elements are in the array, you can pass that value as a second argument:

Function Prototype 
     void MyFunct(char []); 
     void MyFunct(char [],int); 

Function call 
     MyFunct(ArrayName); 
     MyFunct(ArrayName,HowMany); 

Function Header 
     void MyFunct(AryNm[]); 
     void MyFunct(AryNm[],Num);

Built-in String Functions

The header file string.h provides useful set of string functions. These functions help in manipulating strings. To use these functions, the header file string.h must be included in the program with the statement:

strcat (target, source)

The strcat() function accepts two strings as parameters and concatenates them, i.e. it appends the source string at the end of the target.

/* Sample program using strcat() */ 
#include <stdio.h>
#include <string.h>
void main(void) 
{ 
    char name1[]= "Ash"; 
    char name2[]= "wini"; 
    strcat(name1, name2); 
    printf("\n"); 
    puts(name1); 
}

Output:

Ashwini

strcmp (string1, string2)

The function strcmp() is used to compare two strings. This function is useful while writing program for ordering or searching strings.
The function accepts two strings as parameters and returns an integer value, depending upon the relative order of the two strings.

Return value Description
Less than 0 If string1 is less than string2
Equal to 0 If string1 and string2 are identical
Greater than 0 If string1 is greater than string2
/* Sample program to test equality of two strings using strcmp() */# include <stdio.h>
# include <string.h>
void main(void) 
{ 
   char str1[10]; 
   char str2[10]; 
   int result; 
   printf("\n*** Comparing two strings ***\n"); 
   fflush(stdin); /* flush the input buffer */ 
   printf("Enter first string\n"); 
   scanf("%s", str1); 
   fflush(stdin); 
   printf("\nEnter second string\n"); 
   scanf("%s", str2); 
   result = strcmp(str1, str2); 
   if(result < 0) 
       printf("\nString2 is greater than String1 ..."); 
   else if(result == 0) 
       printf("\nBoth the Strings are equal.."); 
   else 
       printf("\nString1 is greater than String2 ..."); 
}

The function strcmp() compares the two strings, character by character, to decide the greater one. Whenever two characters in the string differ, the string that has the character with a higher ASCII value is greater.

E.g. consider the strings hello and Hello!

The first character itself differs. The ASCII code for h is 104, while that for H is 72. Since the ASCII code of h is greater, the string hello is greater than Hello!. Once a difference is found, there is no need to compare the other characters of the strings; hence, function returns the result.

strcpy(target, source)

The strcpy() function copies one string to another. This function accepts two strings as parameters and copies the source string character by character into the target string, up to and including the null character of the source string.

/* Sample program using strcpy() function */ 
# include <stdio.h>
# include <string.h>
void main(void) 
{ 
    char name1[]= "Ash"; 
    char name2[]= "win"; 
    printf("\n** Before Copying two strings are **\v"); 
    printf("%s\t%s", name1, name2); 
    strcpy(name1, name2); 
    printf("\n** After Copying two strings are **\v"); 
    printf("%s\t%s\n", name1, name2); 
}

Output:

** Before Copying two strings are ** 
            Ash              win 
** After Copying two strings are ** 
            win              win

strlen(string)

The strlen() function returns an integer value, which corresponds, to the length of the string passed. The length of a string is the number of characters present in it, excluding the terminating null character.

/* Sample Program using strlen() function() */ 
# include <stdio.h>
# include <string.h>
void main(void) 
{ 
    char arr1[10]; 
    int i, len; 
    printf("\nEnter string :\n"); 
    scanf("%[^\n]", arr1); 
    printf("\nThe length of the string is %d", strlen(arr1)); 
}

There are many more String manipulation functions in <string.h>. The more useful ones can be listed here.

TFunctionT TPrototypeT MeaningT
strcat char *strcat(char *str1, const char *str2) Appends the string pointed to by str2 to the end of the string pointed to by str1. The terminating null character of str1 is overwritten. Copying stops once the terminating null character of str2 is copied. If overlapping occurs, the result is undefined.
strncat char *strncat(char *str1, const char *str2, size_t n); Appends the string pointed to by str2 to the end of the string pointed to by str1 up to n characters long
strchr char *strchr(const char *str, int c) Searches for the first occurrence of the character c (an unsigned char) in the string pointed to by the argument str. The terminating null character is considered to be part of the string.
strncmp int strncmp(const char *str1, const char *str2, size_t n) Compares at most the first n bytes of str1 and str2. Stops comparing after the null character
strcpy char *strcpy(char *str1, const char *str2) Copies the string pointed to by str2 to str1. Copies up to and including the null character of str2
strerror Tchar *strerror(int TerrnumT)T Searches an internal array for the error number errnum and returns a pointer to an error message string.
strlen size_t strlen(const char *str) Computes the length of the string str up to but not including the terminating null character. Returns the number of characters in the string
Related Post