Arrays
Arrays
Arrays
Topics to be covered:
1. Arrays
1. Arrays
● Arrays are data structures consisting of related data items of the same type.
● A group of contiguous memory locations that all have the same type.
● We refer to a particular location or element in an array by (1) array’s name and
(2) position number of the particular element in the array.
The following definition reserves 10 elements for integer array A, which has indices in
the range 0-9.
Index Index Index Index Index Index Index Index Index Index
=0 =1 =2 =3 =4 =5 =6 =7 =8 =9
The following definition reserves 100 elements for character array C and 50 elements
for double array D:
● If there are fewer initializers than elements in the array, the remaining elements
are initialized to zero.
● Example: int A[10] = {0}; //initializes entire array to zeros.
Index Index Index Index Index Index Index Index Index Index
=0 =1 =2 =3 =4 =5 =6 =7 =8 =9
0 0 0 0 0 0 0 0 0 0
● The array definition: int B[4] = {11, 12, 13, 15, 45}; causes a syntax error because
there are five initializers and only four array elements.
● If the array size is omitted from a definition with an initializer list, the number of
elements in the array will be the number of elements in the initializer list.
● Example: int n[] = {100, 3, 40, 59, 6, -7}; will create a six element array initialized
with the values indicated.
Index=0 Index=1 Index=2 Index=3 Index=4 Index=5
100 3 40 59 6 -7
● In C, arrays and pointers are different. They seem similar because array name
gives address of first element and array elements are accessed using pointer
arithmetic. See array vs pointer in C for details.
● Arrays are always passed as pointers to functions. See this for details.
● Like other variables, arrays can be allocated memory in any of the three
segments, data, heap, and stack. Dynamically allocated arrays are allocated
memory on heap, static or global arrays are allocated memory on the data
segment and local arrays are allocated memory on the stack segment.
Pointer Array
It is declared as -: It is declared as -:
A pointer variable can store the A array can store the number of
address of only one variable at a time. elements the same size as the size of
the array variable.
Exercise problems: