Page 75 - DCAP407_DATA_STRUCTURE
P. 75
Data Structure
4.5 Pointers and Arrays
Array is a group of elements (homogenous type) which is stored in contiguous memory locations. The
concept of arrays is similar to pointers. An array can be considered as an internal or hidden pointer
since one element in the array is stored adjacent to another. The identifier of an array is equivalent to
the address of the first element since a pointer is equal to the address of the first element which it points
to.
int num[20];
int *p;
For the above example, the following assignment operation is valid:
p = num;
After the execution of this instruction, p and num are equal and will have the same properties. Here, the
only difference is that, we can change the value of the pointer p by another value, while the num will
always point to the first 20 elements of type int which was defined. Unlike p (ordinary pointer),
numbers in an array are considered as a constant pointer. Hence, the following is not valid.
num = p;
Since num is an array, it operates as a constant operator. Therefore, it is not possible to assign value to
it.
#include<stdio.h>
void main()
{
int num[5], x;
int *p;
p = num;
*p = 10;
p++;
*p = 20;
p = &num[2];
*p = 30;
p = num + 3;
*p = 40;
p = num;
*(p+4) = 50;
for (x=0;x<5; x++)
printf (“%d “, num[x]);
getch();
}
Output: 10 20 30 40 50
In this example:
1. An array num is assigned to pointer p.
2. A value is assigned to the memory location pointed by *p.
3. The pointer p is incremented to point to the next location.
4. Steps 2 and 3 are repeated for all the values.
Bracket sign operator [ ] or dereference operator is known as offset operator. Similar to *, the offset
operator dereferences the variable it follows, but also adds the number between the brackets to the
address being dereferenced.
68 LOVELY PROFESSIONAL UNIVERSITY