Re: struct with indeterminate array(size)
Re: struct with indeterminate array(size)
- Subject: Re: struct with indeterminate array(size)
- From: Brian Hook <email@hidden>
- Date: Wed, 03 Oct 2001 23:37:52 -0700
At 03:20 PM 10/4/01 +1000, Chris Pocock wrote:
typedef struct tcPoint
{
GLfloat x;
GLfloat y;
GLfloat z;
}tcPoint;
typedef struct tcPointList
{
int size;
tcPoint points[];
}tcPointList;
As far as I know, this isn't strictly ANSI C (it's a non-standard extension
that some compilers support, similar to if you had "points[ 0 ]").
If your app is doing what I think it's doing (*shudder*), then the points
field is a syntactic helper for a variable length array. To wit:
tcPointList *p = malloc( sizeof( tcPointList ) + sizeof( tcPoint ) * nPoints );
p->size = nPoints; //or possibly the total size of allocated memory, not
sure in your case
The advantage is that you can now access:
p->points[ 4 ]
with a nice clean syntax and with a single allocation for tcPointList,
instead of doing things the more correct (but less pretty) way, which is to
make points a pointer and allocate it independently of the allocation for
the tcPointList struct:
tcPointList p;
p.points = malloc( sizeof( tcPoint ) * nPoints );
The downside of the above is that memory is more fragmented since you've
allocated two separate chunks of memory.
If I were you, I would try making points[] into points[1] and hope it still
works. Without the rest of the code it's hard to tell what it's really
doing. Replacing points[] with *points won't do the right thing, but if
you massaged it a bit it might:
pl->points = &pl->points[ 0 ];
Assuming you still did a single big malloc.
Brian