Arrays and pointers

Pointers and arrays are so closely related. An array declaration such as int arr[ 5 ] will lead the compiler to pick an address to store a sequence of 5 integers, and arr is a name for that address. The array name in this case is the address where the sequence of integers starts. Note that the value is not the first integer in the sequence, nor is it the sequence in its entirety. The value is just an address.

Now, if arr is a one-dimensional array, then the address of the first array element can be written as &arr[0] or simply arr. Moreover, the address of the second array element can be written as &arr[1] or simply (arr+1). In general, address of array element (i+1) can be expressed as either &arr[ i] or as (arr+ i). Thus, we have two different ways for writing the address of an array element. In the latter case i.e, expression (arr+ i) is a symbolic representation for an address rather than an arithmetic expression. Since &arr[ i] and (ar+ i) both represent the address of the ith element of arr, so arr[ i] and *(ar + i) both represent the contents of that address i.e., the value of ith element of arr.

Note that it is not possible to assign an arbitrary address to an array name or to an array element. Thus, expressions such as arr, (arr+ i) and arr[ i] cannot appear on the left side of an assignment statement. Thus we cannot write a statement such as:

&arr[0] = &arr[1]; /* Invalid */

However, we can assign the value of one array element to another through a pointer, for example,

ptr = &arr[0]; /* ptr is a pointer to arr[ 0] */
arr[1] = *ptr; /* Assigning the value stored at address to arr[1] */

Here is a simple program that will illustrate the above-explained concepts:

/* Program that accesses array elements of a one-dimensional array using pointers */
# include<stdio.h>
main()
{
int arr[ 5 ] = {10, 20, 30, 40, 50};
int i;
for (i = 0; i < 5; i++)
{
printf ("i=%d\t arr[i]=%d\t *(arr+i)=%d\t", i, arr[i], *(arr+i));
printf ("&amp;arr[i]=%u\t arr+i=%u\n", &amp;arr[i], (arr+i)); }
}

OUTPUT:

i=0 arr[i]=10 *(arr+i)=10 &arr[i]=65516 arr+i=65516
i=1 arr[i]=20 *(arr+i)=20 &arr[i]=65518 arr+i=65518
i=2 arr[i]=30 *(arr+i)=30 &arr[i]=65520 arr+i=65520
i=3 arr[i]=40 *(arr+i)=40 &arr[i]=65522 arr+i=65522
i=4 arr[i]=50 *(arr+i)=50 &arr[i]=65524 arr+i=65524

Note that i is added to a pointer value (address) pointing to integer data type (i.e., the array name) the result is the pointer is increased by i times the size (in bytes) of integer data type. Observe the addresses 65516, 65518 and so on. So if ptr is a char pointer, containing addresses a, then ptr+1 is a+1. If ptr is a float pointer, then ptr+ 1 is a+ 4.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: