Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 5 Apr 2017 19:53:38 -0500
From:      Benjamin Kaduk <kaduk@mit.edu>
To:        Mario Lobo <lobo@bsd.com.br>
Cc:        freebsd-questions@freebsd.org, FreeBSD Hackers <freebsd-hackers@freebsd.org>
Subject:   Re: [OFF-TOPIC] C question
Message-ID:  <20170406005338.GR30306@kduck.kaduk.org>
In-Reply-To: <20170405132251.536ab064@Papi>
References:  <20170405132251.536ab064@Papi>

next in thread | previous in thread | raw e-mail | index | archive | help
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
StackOverflow.

> 
> 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
pointers.

-Ben

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.



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20170406005338.GR30306>