Pointers and arrays C

Pointers and array are closely related to each other. Pointers can be used in all places where arrays are used.
If we have an array int n[5].
And a pointer to an integer int *pt.

Then pt = &n[0] or pt = n (since name of array is synonym for address of first element). ,sets ‘pt’ to point to the 0th element of n. i.e. ‘pt’ to contains the address of n[0].

pt + 1 points to the next element of array i.e. n[1] and
pt+i points to the ith element of the array
if pt points to n[0]
*(pt + 1) are contents of n[1] and
*(pt + i) are contents of n[i]

The following table gives a clear picture.

n Array of integers
pt pointer to integer

Pointers and arrays
Example (2) prints the value and address of each element using pointer as well as array to show the relation between the two.
/* Program prints the value and address of elements in an array
using array as well as pointer to show relation between the two */

The combination of array name with its subscript is equivalent to the combination of pointer with its offset.
Now let us write example(1) in array topic using pointers.

array topic using pointers

/* example (1) in array chapter rewritten using pointers
to show the relation between arrays and pointers */

Here pt is a pointer to an integer. pt = marks, assign pt to point to the first element of array ‘marks’ .Since scanf requires address of variable, as i changes from 0 to 9, (pt + i) gives the address of corresponding array element. *(pt + i) gives the value at the address (pt + i) points to.

It is to keep in mind that a pointer is a variable but array name is not a variable, hence assignment, increment, decrement operations can be done on pointers but not on array names.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C Topics