An array is a collection of same type of elements which are sheltered under a common name.
Instead of declaring individual variables, such as elem0, elem1, ...one can declare one array variable such as elem and use elem[0], elem[1], ...to represent individual variables. A specific element in an array is accessed by an index.
Example
+===================================================+
| elem[0] | elem[1] | elem[2] | elem[3] |
+===================================================+
Defining an Array
type arrayName [ arraySize ]; //single-dimensional array declaration
<type> can be any valid C data type.
<arraySize> must be an integer constant greater than zero
Initializing an Array
Example: Integer Array - Individual Initialization
int a[5];
int i = 0;
for(i=0;i<sizeof(a);i++)
{
a[i] = i;
}
Example: Integer Array - Initializing array at the time of declaration.
int a[] = {1,2,3,4,5};
Example: String Initialization
char s[] = "Hello";
or
char s[] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Identical to the previous one
Example: Array of Pointers
int main()
{
char *ptr1 = "Pradeep";
char *ptr2 = "Kohli";
char *ptr3 = "India";
//Declaring an array of 3 char pointers
char* a[3];
// Initializing the array with values
a[0] = ptr1;
a[1] = ptr2;
a[2] = ptr3;
}
Example: Pointer to an Array
type (*arrayName)[arraySize]
For example :
int(*p)[5];
Difference between a pointer and an array
All the above example can give a mislead about an array and can feel also like a pointer. But here are few points which differentiates the pointer with an array -
- A pointer is a place in memory that keeps address of another place inside where as an array is a single, pre allocated chunk of contiguous elements (all of the same type), fixed in size and location.
Pointer can’t be initialized at definition (it first need to be allocated). Array can be initialized at definition.
int num[] = { 1, 2, 3};
- Pointer is dynamic in nature. The memory allocation can be resized or freed later. where as arrays are static in nature. Once memory is allocated , it cannot be resized or freed dynamically.
- Array name is constant while pointer name is variable.