Deniz Bahar wrote:
Hello all,
Often times programs in C have arrays used as buffers and shared
among different sections of code. The need arises to have position
indicators to point to different parts of an array (example: point to
top of stack). Before I even got K&R2 I used to just define extra
pointers to types equal to the element type of the arrays to act as
indicators. Now flipping through K&R2, I see they use int variables
to act as "offsets." What do you experts think of these two methods?
What would be the advatages the "better" method has over the other?'
Are you sure K&R2 didn't just do that early on in the book because
pointers weren't covered yet?
--------------
Example of what I am talking about in question above (SIZE, VALUE are
symbolic constants).
Method 1: Pointers
===================
/* array used as a buffer shared among functions */
T buffer[SIZE];
/* pointer used to point to positions(elements) in buffer */
T *position;
This instrument for holding a position holds a lot of information. It
has a reference type equal to the type of each member of the buffer,
and it holds an address of a member of the buffer. It does not require
a "base" address for use, or any other variables/values.
/* example of use */
*position++ = VALUE;
Method 2: Index Ints
====================
/* array used as a buffer shared among functions */
T buffer[SIZE];
/* int used to designate offset from first element of buffer */
int position;
This instrument for holding a position holds much less information.
It's type is unrelated to the type of the array. It does not hold a
value that has any meaning on it's own. It can't do it's work without
being part of a larger expression that provides the base address for
the array.
/* example of use */
buffer[position++] = VALUE;
I prefer the pointer, because it can be readily passed around as
arguments to functions and hold enough information on it's own for
those functions to access the array. This allows functions to only
require 2 arguments (pointer and array size), instead of three (offset
integer, &array[0], size) - for strings the size isn't required.
Notice, library functions (like strstr strchr, etc.) usually return a
pointer to the actual element, instead of an offset. Imagine if strstr
returned an offset, then you'd have to capture this value into an
interger object, then use it with a pointer to the first character of
the string for dereferencing. As it is, you can simply use the return
value (without even storing it in a temp variable) to do many
meaningful things.
example:
if(strchar(string, '\o') == string)
{
puts("empty string");
}
That's the beauty of a pointer to an array element, it holds a enough
information to be useful on its own.