by Dinesh Thakur Category: Array

Pointers and Arrays : Data objects in an array can be referenced through pointers instead of using array subscripts. The data type of such a pointer is referred to as "pointer to array of type". The array name itself behaves like a pointer, so there are several alternative methods to accessing array elements. For example :


int x[5] = { 0, 1, 2, 3, 4 }; /* Array x declared with five elements */

int *p = x; /* Pointer declared and initialized to point */

/* to the first element of the array x */

int a, b;

a = *(x + 3); /* Pointer x incremented by twelve bytes */

/* to reference element 3 of x */

b = x[3]; /* b now holds the same value as a */


In the previous example, a receives the value 3 by using the dereferencing operator (*). b receives the same value by using the subscripting operator For more information on the different unary operators.


Note that the assignment of a was a result of incrementing the pointer to x . This principle, known as scaling, applies to all types of pointer arithmetic. In scaling, the compiler considers the size of an array element when calculating memory addresses of array members. For example, each member of the array x is 4 bytes long, and adding three to the initial pointer value automatically converts that addition to 3 * (the size of the array member, which in this case is 4). Therefore, the intuitive meaning of z = *(y + 3); is preserved.


When passing arrays as function arguments, only a pointer to the first element of the array is passed to the called function. The conversion from array type to pointer type is implicit. Once the array name is converted to a pointer to the first element of the array, you can increment, decrement, or dereference the pointer, just like any other pointer, to manipulate data in the array. For example :


int func(int *x, int *y) /* The arrays are converted to pointers */


*y = *(x + 4); /* Various elements of the arrays are

accessed */



Remember that a pointer is large enough to hold only an address; a pointer into an array holds the address of an element of that array. The array itself is large enough to hold all members of the array. When applied to arrays, the size of operator returns the size of the entire array, not just the size of the first element in the array.


About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles