I am new to C programming and this type of thing appears. As a simple example, suppose I have a struct http_header with some char pointers:
struct http_header { char* name; char* value; };
I want to populate http_header , where value is an int string representation. I “feel” how, semantically, I should be able to write a function that takes a null header pointer, a name string and int and fills the header accordingly.
void fill_header(struct http_header *h, char* name, int value) { h->name = name; char *value_str = malloc(100); sprintf(value_str, "%d", value); h->value = value_str; } int main(int argc, const char * argv[]) { struct http_header h; char *name = "Header Name"; int val = 42; fill_header(&h, name, val); ... free(h.value); }
Here, the call code reads exactly as my intention, but in this case I create the value string dynamically, which means that I will have to free it later. It doesn't smell me; it seems that the caller knows too much about fill_header implementation. And in real implementations, it may not be so simple to find out what to do for free: consider populating the http_header array, where only one of them should have its own malloc ed value.
To get around this, I would need to create a string in advance:
void fill_header2(struct http_header *h, char* name, char *value_str) { h->name = name; h->value = value_str; } int main(int argc, const char * argv[]) { struct http_header h; char *name = "Header Name"; int value = 42; char value_str[100]; sprintf(value_str, "%d", value); fill_header2(&h, name, value_str); }
As this model continues down the chain of structures with pointers to other structures, I end up doing so much work in the top-level functions, which, apparently, are hardly worth the level that is lower than the level. In addition, I essentially donated to “fill out the headline with an int idea,” which I decided to write first. Am I missing something? Is there any choice of template or design that will make my life easier and keep my calls to functions expressing my intentions?
PS Thanks to everyone at Stackoverfow for being the best professor I have ever had.