Thursday, September 22, 2011

array declaration in c


Declaration of an Array in c and c++
Declaration of an array takes data_type of the elements to be stored, variable name followed by the size of the array wrapped within square brackets as below:

data_type variableNameOfArray[no_elements]

Example:

int employee[5] = {10,20,30,40,50};

where employee is the name of a single dimensional array variable, that can hold 5 variables of integer type. So, the number 5 indicates the size of the array employee.


Where "0", "1", "2", "3", "4" shows the indices of the array employee. Any element of an Array, can be accessed by using it's respective index inside [] as below:

printf("%d", employee[2]);

This will access and print the 3rd element i.e. 30 of the Array employee.


Declaring array as a String



Before the string class, the abstract idea of a string was implemented with just an array of characters. For example, here is a string:

char label[] = "Single";

What this array looks like in memory is the following:
------------------------------
| S | i | n | g | l | e | \0 |
------------------------------
where the beginning of the array is at some location in computer memory, for example, location 1000.


Note: Don't forget that one character is needed to store the nul character (\0), which indicates the end of the string.


A character array can have more characters than the abstract string held in it, as below:

char label[10] = "Single";

giving an array that looks like:

------------------------------------------
| S | i | n | g | l | e | \0 |   |   |   |
------------------------------------------

(where 3 array elements are currently unused).

Since these strings are really just arrays, we can access each character in the array using subscript notation, as in:
/*

 * in C++

 */
 cout << "Third char is: " << label[2] << endl;


/*

 * in C

 */
 Printf ("Third char is: %c\n",label[2]);

which prints out the third character, n. 

A disadvantage of creating strings using the character array syntax is that you must say ahead of time how many characters the array may hold. For example, in the following array definitions, we state the number of characters (either implicitly or explicitly) to be allocated for the array.

char label[] = "Single"// 7 characters
char label[10] = "Single";

Thus, you must specify the maximum number of characters you will ever need to store in an array. This type of array allocation, where the size of the array is determined at compile-time, is called static allocation.

No comments:

Post a Comment