Explain about arrays and pointers

Estudies4you
Q27. Explain about arrays and pointers.
Answer :

Relation between Arrays and Pointers
In C++, a strong relationship exists between arrays and pointers. Any operation that can be done using an array indexing can also be achieved with pointers: However, pointer operations are faster than array operations.
The declaration statement is,
int a[6];
It defines an integer array ‘a’ of size 6. That is, this statement allocates a block of 6 consecutive locations in memory named as a[0], a[1]. ........ , a[5] as shown below,
The array name with subscripting i.e., a[i] refers to the ith element of an array. For example, a[0] refers to the zeroth element of array ‘a’
Consider the declarations,
int a[6], *ptr;
ptr = &a[0];
Here, the first declaration defines an integer array of size 6 and a pointer to an integer. The second declaration assigns the base address of array ‘a’ to the ‘ptr’ variable. The base address of ‘a’ can also be assigned as ptr = a;
This is shown in figure below,
Then the assignment statement y = *ptr; copies the contents of a[0] into ‘y’.
If a pointer variable ‘ptr’ points to an array ‘a’ then ‘ptr’ points to the zeroth element, ptr+1 points to the next element, ptrt+i points to i, elements after ptr, and ptr-ith points to i elements before ptr. That is the contents of a{i] can be accessed using
pointer as *(ptr + i), whereas ptr + i returns the address of a[i].
An array name is itself an address or pointer. Hence, array elements can be.accessed without using the subscripting. That is a[i] can also be written as *(a + i). Similarly, the address of an array element can be accessed using &a[i] or a +i. Both of these statements are identical. Here a + i gives the address of the i element beyond ‘a’.
Using pointers ptr[i] and *(ptr + i) are identical. In short, an array-and-index expression is equivalent to the expression written as a pointer and an offset.
There is a difference between a pointer and an array. Since, a pointer is a variable it can be assigned incremented or decremented like any other variable. For example, ptr=a and ptr ++ are the valid statements. In contrast to this, since an array name is not a variable, the statements like a = ptr and a++ are invalid.
To Top