Search code examples
carraysmallocstructurerealloc

Flexible Arrays in C99


NOTE: I've re written the original question to make it much more clear.

I have a function called

VcStatus readVcard( FILE *const vcf, Vcard **const cardp )

vcf is an open file I will read, and cardp is a pointer to the start of an array of cards. a file will have multiple cards in it.

readVCard reads the file a line at a time, and calls the function parseVcProp to indentify keywords in the line, and assign them to the appropriate place in a structure.

Here are the structures

 typedef struct {    // property (=contentline)
    VcPname name;       // property name

    // storage for 0-2 parameters (NULL if not present)
    char *partype;      // TYPE=string
    char *parval;       // VALUE=string

    char *value;        // property value string
    void *hook;         // reserved for pointer to parsed data structure
} VcProp;

typedef struct {    // single card
    int nprops;         // no. of properties
    VcProp prop[];      // array of properties
} Vcard;

typedef struct {    // vCard file
    int ncards;         // no. of cards in file
    Vcard **cardp;      // pointer to array of card pointers
} VcFile;

So a file contains multiple cards, a card contains multiple properties, etc.

The thing is, a single card can any have number of properties. It is not known how many until you are done reading them.

Here is what I do not understand.

How must I allocate the memory to use parseVcProp properly?

Each time I call parseVcProp, i obviously want it to be storing the data in a new structure, so how do i allocate this memory before hand? Do i just malloc(sizeof(VcProp)*1)?


Solution

  • Vcard *getcards(int n) {
      Vcard *c = malloc(sizeof(Vcard) + sizeof(VcProp) * n);
      c->nprops = n;
      return c;
    }