[OFF-TOPIC] C question

Benjamin Kaduk kaduk at mit.edu
Thu Apr 6 00:58:55 UTC 2017

On Wed, Apr 05, 2017 at 01:23:16PM -0300, Mario Lobo wrote:
> Hi There !
> I don't know if this list is appropriate for this. 
> if it isn't, please point me to the right direction.

It would probably be more appropriate on something like

> How can I dynamically change the level of indirection?
> How can I dynamically switch:
> ----------------
> KFNODE ***Nodes; to  KFNODE ****Nodes;
> ----------------
> Nodes = (KFNODE ***) malloc(5 * sizeof(KFNODE **));
> to Nodes = (KFNODE ****) malloc(5 * sizeof(KFNODE ***));
> ----------------
> and so forth?
> Is this possible at all?

It is a rather unnatural thing to want to do, so the solution would
also be rather unnatural.  It seems, though, that you could have a
loop construct that uses void* and void** for all levels except for
the leaf, since the underlying property of the non-leaf allocations
is that they are to hold pointers.  As you prepare to go to the next
layer of indirection  you cast the pointers from void* to void** and
dereference them.  Once your depth gets to the last level then you
can cast he void* to KFNODE* and actually handle the leaf elements.

But as I said, this is rather unusual style to do, and would require
replacing the x[a][b][c] with a loop that dereferences successive


P.S. All those extra allocations for intermediate arrays add up to a
fair bit of storage, and the extra cost of all the pointer
indirections does, too.  Sometimes it's more efficent to just
allocate a "flat" array of KFDNODE[x*y*z] and manually do index
arithmetic to emulate a multi-dimensional array.

More information about the freebsd-questions mailing list