One Dimensional Arrays
An array can be defined as a contiguous area in memory which can be referred to by a common name. Arrays are used to group set of similar data .
Each element of the array can be referred to by
In the C language subscripting begins from zero, and can be any valid integer or integer variable.
A single dimensional array in C is declared as follows:
type arrayname[n];
The array are internally stored as a contiguous set of similar data types. The value n in the array declaration defines the number of elements and hence the dimension of the array .
Defining Arrays
Consider the following definitions:
int numbers[10];
This defines an integer array called numbers which can hold 20 integers which will be stored in the elements numbers[0] to numbers[19].
char string[8];
This defines an character array called string which can hold 7 characters which will be stored in the elements string[0] to string[7].
Initialisation of Arrays
An array can be initialised when declared by specifying the values of some or all of its elements.
Direct initialisation is possible in two ways:
char name[4]={'n','i','v','\0'};
char name[4]={"niv"};
Initialisation can also be done inside the function, after the array has been declared, by accepting the values.
Working with Arrays
Array elements are referenced by using subscripts . Since subscripts are integers, array manipulation is possible through the use of variables.
Consider the following program segment to calculate the length of a given string:
#include <stdio.h>
char thought[60]={"Love makes the life beautiful"};
main()
{
int i=0;
char ans='y';
printf("The thought of the day is : %s", thought);
printf("Would you like to change it?");
ans=getchar();
if (ans= ='y')
{
printf("Enter new thought for the day");
gets(thought);
printf("\nNew thought of the day is : %s",thought);
}
}
Array Addressing
The definition:
char string[11];
defines an array, string to store ten elements along with a string terminator, the NULL character.In the memory, string refers to the starting position or address of the area which gets allocated for storing the elements of the array.
To arrive at the particular element, the following formula is used:
starting address + (Offset number * Scaling factor of the array)
where Scaling factor is the number of bytes of storage space required by specific data type.
The product of scaling factor and the offset number gives the number of bytes to be added to the starting address of the array to get to the desired element.
This is why the first element of an array is referred to be the subscript 0.The element string[0] is 0 bytes away from the starting address given by string.
Copyright © 2008 Manikkumar. All rights reserved.