On Fri, 05 Mar 2004 16:15:14 GMT, Grant Austin <ga*****@foo.foo.bar.net>
wrote:
What would be the correct syntax for setting up
a dynamic array of structs?
You're quite close.
Suppose you have a struct declared:
struct relation {
FILE * binFile;
unsigned int numAttrs;
struct attrList * relAttrs; /* definition shown at end of post */
Because attrList is already a typedef for a struct (well, it will be), this
isn't quite right. See my re-organized code below.
};
typedef struct relation relHeader;
The array only has to be sized once. The size is read from a text
file.
Currently I have something like this:
#include <stdio.h>
int main(void){
unsigned int relCount = 2;
Does "2" really mean 2 structs you'll be reading? If so, why are you
subtracting 1 below? Are you possibly confusing "size" with subscripting
expressions?
relHeader Headers[relCount-1];
return 0;
}
I would prefer to be able to define Headers as:
relHeader * Headers;
No prob.
And then malloc space for whatever size I need.
When I try:
Headers = malloc(sizeof(*Headers) * (relCount-1))
If you're malloc-ing relHeader objects, you just need to specify the size
of a relHeader object (see code below). And again, I suspect you don't want
to be subtracting that 1.
I get a warning and a syntax error as follows:
p3.c:26: warning: assignment makes pointer from integer without a cast
p3.c:26: syntax error before "Headers"
Looks like you didn't include a required header file. See my code below.
What I have will work well enough for my purposes. If it's something
simple I'm missing I'd like to fix it.
Regards,
Grant
struct attribute {
struct attribute * next;
unsigned int attrLen;
char type;
char * attrName;
};
typedef struct attribute attrList;
Here's the rolled-up version:
#include <stdio.h>
#include <stdlib.h> /* for malloc */
struct attribute {
struct attribute * next;
unsigned int attrLen;
char type;
char * attrName;
};
typedef struct attribute attrList;
struct relation {
FILE * binFile;
unsigned int numAttrs;
/* struct attrList * relAttrs; /* definition shown at end of post */
attrList * relAttrs; /* note: no 'struct' */
};
typedef struct relation relHeader;
int main(void){
unsigned int relCount = 2;
relHeader * Headers;
/* Headers = malloc(sizeof(*Headers) * (relCount-1)) */
Headers = malloc(sizeof(relHeader) * relCount);
return 0;
}
HTH,
-leor
Leor Zolman
BD Software
le**@bdsoft.com www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at
www.bdsoft.com/tools/stlfilt.html