Re: which is the better way to declare dynamic single dimension array inside struct

From: The Real OS/2 Guy (os2guy_at_pc-rosenau.de)
Date: 02/27/04


Date: Fri, 27 Feb 2004 09:49:30 +0000 (UTC)

On Fri, 27 Feb 2004 05:45:07 UTC, geetesh_game@yahoo.co.in (Geetesh)
wrote:

> Recently i saw a code in which there was a structer defination similar
> as bellow:
> struct foo
> {
> int dummy1;
> int dummy2;
> int last[1]
> };
> In application the above array is always allocated at runtime using
> malloc.In this last member of the structer "int last[1]" is not
> actually used as array with single element but when alloacting space
> for struct foo extra memory is allocated and last is used as array
> with more then one element. my question is what are the advantages of
> using the above defination instead of the shown below.
> struct foo
> {
> int dummy1;
> int dummy2;
> int *last;
> };
> The only advantage i can think of is that we will have to call single
> malloc in first declaration and two malloc in second declaration and
> also that in first declaration all the memeory allocated will be
> contigous which may lead to less framgmentation and better cache
> utilization. My question is does using first defination for accessing
> of elements faster when compared to second. If yes why?
> Thanks in advance.

It save memory. At lest the amount of memory a pointer costs.
It saves time as not every time are 2 malloc() required to fill a
whole struct.

No, it is NOT undefined behavior as Jack Klein says. But it is
implementation defined.

Look at the APIs of your OS. The chance is high that there is at least
one or more APIs who deliver or receive such kind of structs.

-- 
Tschau/Bye
Herbert
Visit http://www.ecomstation.de the home of german eComStation