[A89] Re: Pointers and Matricies
[Prev][Next][Index][Thread]
[A89] Re: Pointers and Matricies
Uhoh -- I don't fell very confident when disagreeing with Zeljko, although
my understanding is different. Zeljko, if I'm wrong here, please correct me
=)
> You can not do
>
> char matrix[5][5]=...
> char **pmatrix=&matrix;
>
> because the pointer pmatrix does not know anything about the width
> of the matrix (it doesn't need to know anything about the height,
> but the width is vital; try to uncover why).
I don't believe that it does need to know the width, because of the way that
C treats multidimensional arrays. The main array contains a list of
pointers to each array. Two dimensional arrays don't contain all values in
one chunk of memory. For instance, I thought that C treats these two
examples identically:
---
char example1[][] =
{{0,1,2,3,4}{5,6,7,8,9}};
---
char example2row1[] =
{0,1,2,3,4};
char example2row2[] =
{5,6,7,8,9};
char * example2[] =
{example2row1, example2row2};
---
The beauty of the second example is that you can reference example2 in the
exact same way as example1, and the compiler only needs to know the size of
the final type (in this case, char). No need to know the height _or the
width_ of the array, it just continually dereferences pointers until it gets
to the innermost array.
Using this method - with multidimensional arrays really just being arrays
with pointers to more arrays - the compiler implementation is extremely
simple, the number of dimensions it can handle are theoretically unlimited,
it's very efficient, and the pointer can be copied and used with array
notation (as we want to do). That's why this implementation of arrays is
used by most all compilers (or at least I thought it is). I believe I read
the explanation of this in Dennis Ritchie's paper on the development of the
C language, available at http://cm.bell-labs.com/cm/cs/who/dmr/chist.html --
although it might have been somewhere else, I'm not quite sure =(
Zeljko, have you tried my (and Olle's) solution on an actually compiler? If
so, which one? I've always been pretty sure that this should be just fine,
based on the reasoning I used above.
-Scott