Friday, October 16, 2009

Pointing to Objects

You can access an element in an array by using a pointer. For instance, given an array, an_array, and a pointer,
ptr_array, if an_array and ptr_array are of the same data type, and ptr_array is assigned with the start address of the
array like this:
ptr_array = an_array;
the expression
an_array[n]
is equivalent to the expression
*(ptr_array + n)
Here n is a subscript number in the array.
In many cases, it's useful to declare an array of pointers and access the contents pointed to by the array through
dereferencing each pointer. For instance, the following declaration declares an int array of pointers:
int *ptr_int[3];
In other words, the variable ptr_int is a three-element array of pointers with the int type.
Also, you can define a pointer of struct and refer to an item in the structure via the pointer. For example, given the
following structure declaration:
struct computer {
float cost;
int year;
int cpu_speed;
char cpu_type[16];
};
a pointer can be defined like this:
struct computer *ptr_s;
Then, the items in the structure can be accessed by dereferencing the pointer. For instance, to assign the value of 1997
to the int variable year in the computer structure, you can have the following assignment statement:
(*ptr_s).year = 1997;
Or, you can use the arrow operator (->) for the assignment, like this:
ptr_s->year = 1997;
Note that the arrow operator (->) is commonly used to reference a structure member with a pointer.

No comments:

Post a Comment