> ~ Online tutorial


Arrays and Pointers
The information about how arrays are stored was not included just for interest. There is another way of looking at arrays which follows the BCPL idea of an array as simply a block of memory. An array can be accessed with pointers as well as with [] square brackets.
The name of an array variable, standing alone, is actually a pointer to the first element in the array.
For example: if an array is declared
float numbers[34];

then numbers is a pointer to the first floating point number in the array; numbers is a pointer in its own right. (In this case it is type `pointer to float'.) So the first element of the array could be accessed by writing:
numbers[0] = 22.3;

or by writing
*numbers = 22.3;

For character arrays, which are dealt with in some depth in chapter 20, this gives an alternative way of getting at the elements in the array.
char arrayname[5];
char *ptr;

for (ptr = arrayname; ptr <= arrayname+4; ptr++)
   {
   *ptr = 0;
   }

The code above sets the array arrayname to zero. This method of getting at array data is not recommended by this author except in very simple computer environments. If a program is running on a normal microcomputer, then there should be few problems with this alternative method of handling arrays. On the hand, if the microcomputer is multi-tasking, or the program is running on a larger system which has a limited manager, then memory ceases to be something which can be thought of as a sequence of boxes standing next to one another. A multi-tasking system shares memory with other programs and it takes what it can find, where it can find it. The upshot of this is that it is not possible to guarantee that arrays will be stored in one simple string of memory locations: it might be scattered around in different places. So
ptr = arrayname + 5;

might not be a pointer to the fifth character in a character array. This could be found instead using the & operator. A pointer to the fifth element can be reliably found with:
ptr = &(arrayname[5]);

Please Give Us Your 1 Minute In Sharing This Post!
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Powered By: BloggerYard.Com

0 comments: