how do you dynamically allocate mult
dan at haddock.UUCP
dan at haddock.UUCP
Sun May 5 08:27:00 AEST 1985
Re: dynamically allocating a two-dimensional array of structures.
C's "integration" of arrays and pointers has led you into
some confusion. Beyond the simplest cases, you should make
your uses follow your declarations EXACTLY. Otherwise you are
liable not to get what you want. In this case, you had
struct fred { int i; int j; };
struct fred (*p)[2][2];
This means that if you want to use p, you must say not
p[1][1]->i
but instead
(*p)[1][1].i
which indirects through the pointer and then subscripts, just
like the declaration says you will. I changed your test program
to do this and it then worked correctly. What the first
expression meant to the compiler, in the context of that
declaration, was something like this. Since p is a pointer, it
can be treated as an array of pointed-to things. In this case a
pointed-to thing is a 2x2 array of struct freds. So choose the
second 2x2 array (first [1]). Now select the second row of that
array (second [1]). Now since a->b is equivalent to (*a)->b,
and (*a) is equivalent to a[0] when applied to arrays, this ->
must actually mean to select the first element in that row and
find member i.
A good rule to remember is that whenever you find yourself declaring
a pointer to an array (as opposed to a pointer to a MEMBER OF the array),
think twice: what you are doing is probably wrong and certainly confusing.
Always declare pointers to point at the first member; then pointer
subscripting will do what you expect. In your case, making the declaration
struct fred (*p)[2];
will enable expressions such as p[1][1].i to work. (Again, when I recompiled
your program with this declaration, and changed your "->" to ".", and fixed
the malloc cast to match the new type of p, it worked correctly.)
Dan Franklin (ima!haddock!dan)
More information about the Comp.lang.c
mailing list