Array definition
Array by definition is a variable that hold multiple elements which has the same data type.
Declaring Arrays
We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name. Here is the syntax:
For example, to declare an integer array which contains 100 elements we can do as follows:
There are some rules on array declaration. The data type can be any valid C data types including structure and union. The array name has to follow the rule of variable and the size of array has to be a positive constant integer.
We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1].
Initializing Arrays
It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name. Here is an example of initializing an integer array.
Array and Pointer
Each array element occupies consecutive memory locations and array name is a pointer that points to the first element. Beside accessing array via index we can use pointer to manipulate array. This program helps you visualize the memory address each array elements and how to access array element using pointer.
Here is the output
list[0] is in 1310568
list[1] is in 1310572
list[2] is in 1310576
list[3] is in 1310580
list[4] is in 1310584
list[0] = 2
list[1] = 1
list[2] = 3
list[3] = 7
list[4] = 8
You can store pointers in an array and in this case we have an array of pointers. This code snippet use an array to store integer pointer.
Multidimensional Arrays
An array with more than one index value is called a multidimensional array. All the array above is called single-dimensional array. To declare a multidimensional array you can do follow syntax
The number of square brackets specifies the dimension of the array. For example to declare two dimensions integer array we can do as follows:
Initializing Multidimensional Arrays
You can initialize an array as a single-dimension array. Here is an example of initialize an two dimensions integer array:
0 comments:
Post a Comment