Reputation: 3986
I'm working on an assignment, and my professor has given us the function prototypes for everything we are supposed to use, as well as the structure definitions.
The purpose of the program is to read .vcf (vCard) files.
We have a function readVcFile which calls readVcard which calls the appropriate functions to read each line and parse it.
Here are the relevant function prototypes to my question:
VcStatus readVcFile( FILE *const vcf, VcFile *const filep );
VcStatus readVcard( FILE *const vcf, Vcard **const cardp );
VcStatus getUnfolded( FILE *const vcf, char **const buff );
What I am having trouble figuring out, is when to allocate memory. From what i understand, most of the pointers are supposed to be a way of returning a value. For instance, I have figured out getUnfolded, which took the pointer to string, and used that pointer to fill up the string with whatever characters were on the line.
Where I am having more trouble is with readVcard.
Remember, readVcFile calls readVcard, and there can be multiple vcards in a vcf file, so it may call more then once. Now my question is, when (and how) should I malloc a vCard. Do i malloc before I call readVcard? And how do I access that vcard once I am in readVcard?
This is all very confusing, so I appreciate any attempts to clarify things for me.
Thanks.
Edit: If it helps, the size of vcards can vary, so I need to use malloc.
Upvotes: 2
Views: 303
Reputation: 7003
(I'm going on the assumption that your assignment is to use these functions, not write them. Please clarify your question if I'm wrong.)
Note that there are two asterisks before readVCard()
's cardp
argument. That means the caller provides a pointer to a pointer, which is another way of telling readVcard()
that it should come up with a pointer to the resulting Vcard
and assign it to whatever pointer the caller provides. This technique is usually used when the function will allocate the memory and the caller is responsible for freeing it:
Vcard *card;
VcStatus status = readVcard(file, &card);
/* card now points at a newly-allocated Vcard */
if ( status == WHATEVER_THE_VALUE_IS_FOR_SUCCESS ) {
/* ... Do something with the card ... */
free(card);
}
The prof should have provided documentation on how the function is supposed to behave, and there should be something in it to the effect of "setscardp
to a pointer to memory allocated to hold the resulting Vcard
structure if the read succeeded." If that bit of information is missing, send the assignment back and request more complete documentation. (And if it's a CS professor, two demerits for sloppy practice!)
Upvotes: 2