UNIT-III
Arrays
Introduction, Operations on Arrays, Arrays as Function
Arguments,Two Dimensional Arrays, Multidimensional Arrays.
Pointers: Concept of a Pointer, Declaring and Initializing
Pointer Variables, Pointer Expressions and Address
Arithmetic, Null Pointers, Generic Pointers, Pointers as
Function Arguments, Pointers and Arrays, Pointer to Pointer,
Dynamic Memory Allocation, Dangling Pointer, Command
Line Arguments.
Array
An Array is defined as the collection of similar type of data items stored at contiguous
memory locations.
Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc.
The Array is the simplest data structure where each data element can be randomly
accessed by using its index number.
Important terms to understand the concept of array:
Element
Index
Advantages of an array:
Arrays represent multiple data items of the same type using a single name.
In arrays, the elements can be accessed randomly by using the index number.
Arrays allocate memory in contiguous memory locations for all its elements. Hence there
is no chance of extra memory being allocated in case of arrays. This avoids memory
overflow or shortage of memory in arrays.
Using arrays, other data structures like linked lists, stacks, queues, trees, graphs etc can
be implemented.
Two-dimensional arrays are used to represent matrices.
Disadvantages of an array:
The number of elements to be stored in an array should be known in advance.
An array is a static structure (which means the array is of fixed size). Once declared the
size of the array cannot be modified. The memory which is allocated to it cannot be
increased or decreased.
Insertion and deletion are quite difficult in an array as the elements are stored in
consecutive memory locations and the shifting operation is costly.
Allocating more memory than the requirement leads to wastage of memory space and less
allocation of memory also leads to a problem.
Properties of an array:
An array is a derived data type, which is defined using basic data types like int, char, float
and even structures.
Array name represents its base address. The base address is the address of the first element
of the array.
Array s index start with 0 and ends with N-1 ,here, N stands for the number of elements.
For example: there is an integer array of 5 elements,then its indexing will be 0 to 4.
Applications of Arrays:
Array stores data elements of the same data type.
Arrays are used to Perform Matrix Operations. We use two dimensional arrays to create
matrix and perform various operations on matrices using two dimensional arrays.
Maintains multiple variable names using a single name. Arrays help to maintain large data
under a single variable name. This avoids the confusion of using multiple variables.
Arrays can be used for sorting data elements. Different sorting techniques like
Bubble sort,
Insertion sort,
Selection sort etc. use arrays to store and sort elements easily.
Arrays can be used for performing matrix operations. Many databases, small and large,
consist of one-dimensional and two-dimensional arrays whose elements are records.
Arrays can be used for CPU scheduling.
Lastly, arrays are also used to implement other data structures like Stacks, Queues, Heaps,
Hash tables etc.
Arrays are used to implement Search Algorithms. We use single dimensional arrays to
implement search algorithms like ...
Linear Search
Binary Search
Different types of an array:
1.One dimensional array (1D) or single dimensional array
2. Two dimensional array (2D) or Multi-dimensional array
1. One dimensional (1D) array or single dimensional array:
In c programming language, single dimensional arrays are used to store list of values of same
data type. In other words, single dimensional arrays are used to store a row of values. In
single dimensional array, data is stored in linear form. Single dimensional arrays are also
called as one- dimensional arrays, Linear Arrays or simply 1-D Arrays.
Declaration of 1D-array:
To declare an array in C, we need to specify the type of the elements and the number of
elements required by an array i.e., size of the elements.
The following is the syntax for declaring 1-D as follows:
data_type array_name[Size];
We can create an array with size and also initialize values to it.
data_type array_name [ size ] = {value1, value2, ...} ;
Syntax for creating an array without size and with initial values
data_type array_name [ ] = {value1, value2, ...} ;
In the above syntax, the data type specifies the type of values we store in that array and
size specifies the maximum number of values that can be stored in that array.
For example:
float mark[5];
Here, we declared an array called mark, of floating-point type and its size is 5. Meaning, it
can hold 5 floating-point values.
In the above memory allocation, all the three memory locations have a common name 'a'. So
accessing individual memory location is not possible directly. Hence compiler not only
allocates the memory but also assigns a numerical reference value to every individual memory
location of an array. This reference number is called "Index" or "subscript" or "indices". Index
values for the above example are as follows...
How to initialize one-dimensional array:
The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index.
Example:
int marks[5];
marks[0]=80; //initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
It is not necessary to define the size of array during initialization. We can also initialize the
size of an array like this:
int marks[]={80,60,70,85,75};
The above example tells that memory is allocated at run time based on the number of
elements given in an array. This is another approach to initialize an array.
The number of elements in the initialization list should be less than the size of array
because index is starts with 0.
If the array size is greater than the list of elements in the array, then it first allocate
memory for the elements and remaining space is filled with zero’s.
Ex: int marks[5]={10,20,30};
If the array elements are greater than the array size, then it shows compilation error.
int age[4]={1,2,3,4,5} // ERROR
How to Access 1D-Array Elements:
In c programming language, to access the elements of single dimensional array we use array
name followed by index value of the element that to be accessed. Here the index value must
be enclosed in square braces. Index value of an element in an array is the reference number
given to each element at the time of memory allocation. The index value of single
dimensional array starts with zero (0) for first element and incremented by one for each
element. The index value in an array is also called as subscript or indices.
Key points:
•Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
•If the size of an array is ‘n’ ,to access last element, the n-1 index is used. In this example,
mark[4].
Example:
•The elements can be accessed from an array with help of index values.
•Suppose declare an array mark with int data type followed by some size i.e. int mark[5];
•The first element is accessed with mark[0], the second element is mark[1] and so on.
How to Read 1D-array values:
How to Writing 1D-array values:
What is Sorting?
Sorting refers to rearrangement of a given array or list of elements
according to a comparison operator on the elements. The comparison
operator is used to decide the new order of elements in the respective
data structure. Sorting means reordering of all the elements either in
ascending or in descending order.
what is Searching? Searching is the process of finding a given value
position in a list of values. It decides whether a search key is present in
Two dimensional Array (2D) or Multidimensional array:
An array of arrays is called as 2D or multi dimensional array. In simple words, an array
created with more than one dimension (size) is called as multi dimensional array. Multi
dimensional array can be of two dimensional array or three dimensional array or four
dimensional array or more. Most popular and commonly used multi dimensional array is
two dimensional array. The 2-D arrays are used to store data in the form of table. We also
use 2-D arrays to create mathematical matrices.
Declaration of Two Dimensional Array:
We use the following general syntax for declaring a two dimensional array...
datatype arrayName [ rowSize ] [ columnSize ] ;
Example:
int array1[2][3] ;
The above declaration of two dimensional array reserves 6 continuous memory locations of
2 bytes (or 4 bytes) each in the form of 2 rows and 3 columns.
Initialization of Two Dimensional Array:
We use the following general syntax for declaring and initializing a two dimensional array
with specific number of rows and columns with initial values.
datatype arrayName [rows][columns] = {{val1, val2, ...},{val3, val4...}...} ;
Example:
int array1[2][3] = { {1, 2, 3},{4, 5, 6} } ;
The above declaration of two-dimensional array reserves 6 contiguous memory locations of
2 bytes each in the form of 2 rows and 3 columns. And the first row is initialized with values
1, 2 & 3 and second row is initialized with values 4, 5 & 6.
We can also initialize as follows...
Example:
int array1[2][3] = {{1, 2, 3},{4, 5, 6}};
(OR)
Another way to initialize value into an array:
int a[2][2];
a[0][0]=10;
a[0][1]=20;
a[1][0]=30;
a[1][1]=40;
Example Program:
Accessing Individual Elements of Two Dimensional Array:
In a c programming language, to access elements of a two-dimensional array we use array
name followed by row index value and column index value of the element that to be
accessed. Here the row and column index values must be enclosed in separate square braces.
In case of the two- dimensional array the compiler assigns separate index values for rows
and columns.
We use the following general syntax to access the individual elements of a two-dimensional
array...
arrayName [ rowIndex ] [ columnIndex ];
ADDRESS IN C:
If you have a variable ‘var’ in your program, ‘&var’ will give you its address in the
memory,where & is commonly called the reference operator.
This notation is seen in the scanf function. It is used in the function to store the user inputted
value in the address of var.
scanf("%d", &var);
POINTERS:
A pointer is a variable whose value is the address of another variable, i.e., direct address of
the memory location. Like any variable or constant, you must declare a pointer before
using it to store any variable address.
Declaration:
Syntax: data_type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the
name of the pointer variable.
Examples:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
Initialization of pointer variable:
The initialization of a pointer variable is similar to other variable initialization, but in the
pointer variable we assign the address instead of value. int *ptr;
int var=10;
ptr = &var;
In the above example we have a pointer variable (*ptr) and a simple integer variable (var).
We have to assign the pointer variable to the address of ‘var’. It means that the pointer
variable ‘*ptr’ now has the address of the variable ‘var’.
REFERENCE OPERATOR (&) AND DEREFERENCE OPERATOR (*):
& is called reference operator which gives the address of a variable. Likewise, there is
another operator that gets you the value from the address, it is called a dereference operator
(*).
Note: The * sign when declaring a pointer is not a dereference operator.
Types Of Pointers.
1.NULL POINTERS: It is always a good practice to assign a NULL value to a pointer
variable in case you do not have an exact address to be assigned. This is done at the time of
variable declaration. A pointer that is assigned NULL is called a null pointer.
2.GENERIC POINTERS or VOID POINTERS:
It is a pointer variable that has void as its data type. It can be used to point to variables of
any type.
void *ptr;
In C, since we cannot have a variable of type void, the void pointer will therefore not
point to any data and thus cannot be dereferenced. We need to typecast a void pointer
to another kind of pointer before using it. It is often used when we want a pointer to
point to data of different types at different time.
3. POINTER TO POINTER OR DOUBLE POINTER
The pointer to a pointer in C is used when we want to store the address of another pointer.
The first pointer is used to store the address of the variable. And the second pointer is used
to store the address of the first pointer. That is why they are also known as double-pointers
Declaration:
int **var; //declares a pointer to pointer of type int
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example:
4. DANGLING POINTERS
Dangling pointers arise when an object is deleted or de-allocated, without modifying
the value of the pointer, so that the pointer still points to the memory location of the de-
allocated memory.
In short pointer pointing to non-existing memory location is called dangling pointer.
Examples:
•Way 1 : Using free or de-allocating memory
First, we declared a character pointer. After running some statements, we freed the memory
that was previously allocated to this pointer. Once the memory is freed, the pointer becomes
a dangling pointer because it is still pointing to a memory location that is no longer valid.
How to Ensure that Pointer is no Longer Dangling ?
After de-allocating memory, initialize pointer to NULL so that pointer will be no longer
dangling. Assigning NULL value means pointer is not pointing to any memory location.
POINTER EXPRESSIONS AND POINTER ARITHMETIC:
Like other variables, pointer variables can also be used in expressions. For example, if p1
and p2 are pointers, then the following statements are valid.
In C, the programmer may add or subtract integers from pointers. We can also subtract one
pointer from the other. We can also use short hand operators with other pointer variables as
we use with other variables.
Let us now summarize the rules for pointer operations:
• A pointer variable can be assigned the address of another variable
(of the same type).
•Prefix or postfix increment and decrement operators can be applied
on a pointer variable.
• An integer value can be added or subtracted from a pointer
variable.
•A pointer variable can be compared with another pointer variable
of the same type using relational operators.
DYNAMIC MEMORY MANAGEMENT:
Dynamic memory management refers to the process of allocating memory to the
variables during execution of the program at run time. This allows you to obtain
more memory when required and release it when not necessary.
There are 4 library functions defined under <stdlib.h> for dynamic memory
allocation.
1.malloc()
•The name malloc stands for "memory allocation".
•It is mainly useful to allocate memory.
•It allocates requested size in bytes and and returns a pointer to the starting address of
memory stack.
•It allocates only one block of memory.
•malloc accepts only one argument.
•The function malloc() reserves a block of memory of specified size and return a pointer of
type void which can be casted into pointer of any form.
Syntax:
ptr = (cast-type*) malloc(byte-size);
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of
memory with size of byte size. If the space is insufficient, allocation fails and returns NULL
pointer.
Example:
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes
respectively and the pointer points to the address of first byte of memory.
2.calloc()
•The name calloc stands for "contiguous allocation".
•It is useful to allocate memory to a pointer variable during execution time.
•It allocates multiple blocks of memory and returns the pointer to the first block.
•It requires two arguments
•The only difference between malloc() and calloc() is that, malloc() allocates
single block of memory whereas calloc() allocates multiple blocks of memory
each of same size and sets all bytes to zero.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of n
elements.
Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements
each of size of float, i.e, 4 bytes.
3. realloc()
If the previously allocated memory is insufficient or more than
required, you can change the previously allocated memory size
using realloc().
Syntax:
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize
4.free()
•Dynamically allocated memory created with either calloc() or
malloc() doesn't get freed on its own. You must explicitly use free()
to release the space.
Syntax:
free(ptr);
This statement frees the space allocated in the memory pointed by
ptr.
Command Line Arguments:
The most important function of C is the main() function. It is mostly defined with
a return type of int and without parameters.
int main()
{
...
}
We can also give command-line arguments in C. Command-line arguments are
the values given after the name of the program in the command-line shell of
Operating Systems. Command-line arguments are handled by the main() function
of a C program.
To pass command-line arguments, we typically define main() with two
arguments: the first argument is the number of command-line arguments and
the second is a list of command-line arguments.
Syntax
int main(int argc, char *argv[])
Here,
argc (Argument Count) is an integer variable that stores the number of
command-line arguments passed by the user including the name of the program.
So if we pass a value to a program, the value of argc would be 2 (one for
argument and one for program name)
argv (Argument Vector) is an array of character pointers listing all the
arguments.
•If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will
contain pointers to strings.
•argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.
For understanding
POINTERS AND ARRAYS:
When an array is declared, compiler allocates sufficient amount of memory to
contain all the elements of the array. Base address i.e address of the first element
of the array is also allocated by the compiler.
Suppose we declare an array arr,
int arr[5] = { 1, 2, 3, 4, 5 };
Assuming that the base address of arr is 1000 and each integer requires two
bytes/four bytes.Here variable arr will give the base address, which is a
constant pointer pointing to the first element of the array, arr[0]. Hence arr
contains the address of arr[0] i.e 1000.
In short, arr has two purpose - it is the name of the array and it acts as a
pointer pointing towards the first element in the array.
arr is equal to &arr[0] by default.
We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;
// or,
p = &arr[0]; //both the statements are equivalent.
Pointer to Array:
We can use a pointer to point to an array, and then we can use that pointer to access
the array elements. Lets have an example,
ARRAY OF POINTERS:
Just like we can declare an array of int, float or char etc, we can also declare an array of
pointers, here is the syntax to do the same.
Syntax: Example:
datatype *array_name[size]; int *arrop[5];
Here arrop is an array of 5 integer pointers. It means that this array can hold the address
of 5 integer variables, or in other words, you can assign 5 pointer variables of type pointer
to int to the elements of this array.