Pointers and Arrays

December 18th, 2009 by Kevin | Posted under C Programming.

Array

An array is a collection of items which share the same characteristics. So we can have an array of integers, array of characters, etc. The important point about arrays is that the elements of the array are located into contiguous locations of memory. This can be used to our advantage in programming.

An integer array is defined as int a[5];

Array

As the diagram above shows, we have defined an array of type integer with six elements in it. The elements of the array are stored sequentially in the memory as shown. Hence they can be accessed by their index as a[0](first element), a[1](second element), a[2], …

Since this array is of type integer, every element is an integer and so each occupies four bytes (depends on the machine) of memory.

A character array is a special kind of array which is also known as a string. What makes the character array special is that it can be used by several functions in the string manipulation library (and also by the user defined functions) because of it’s characteristic of placing a ‘′ escape sequence at the end of the array to indicate the string termination.

Pointers

A pointer is a variable which holds the memory address of another variable. We can have a pointer to any data type we want such as integers, floats, characters, etc. We can also have pointers to other abstract data types that we create (which we will see in later posts).

Pointer Variables

As shown in the figure, p is a pointer variable which points to the address of an integer variable a. The following example will make it more clear.

int *p; /* this is the declaration of the integer pointer. */
int a = 10;

p = &a; /* Here the address of variable a is assigned to pointer p by using the reference operator */
printf("a = %dn", *p); /* Here a is shown to be same as *p where * is the dereference operator */

And then the pointer can be assigned the address of any integer variable as

p = &a;

& is the referencing symbol and * is the de-referencing symbol for the pointer.

Pointers and Arrays

An array is a sequence of elements stored in a contiguous block of memory. So we can consider an array a of 10 elements by representing it with a pointer as shown

int a[10];

int *p = &a[10]; /* pointer to an array */

a[5] = 10;

*(p + 5) = 10; /* same as above statement */

p[5] = 10; /* same as above two statements */

When an array is passed into a function, instead of a copy of the array just a unmodifiable pointer to the first element of the array is passed.

In the next post, I will write about such uses of pointers including others such as call by reference, function pointers.

 

Related Posts:

Tags: , ,

Do you have any comments on Pointers and Arrays ?

Spam protection by WP Captcha-Free