Reputation:
So I am new to C and I have a question that I am hoping someone can help me with. Suppose I have a string.
typedef struct String {
char *value;
int size;
} String;
And what I want to do is initialize this string with a function. My first question is which would be better
bool init_String(String **s, char *p) {
if (s == NULL || *s == NULL) {
return false;
}
(*s)->value = p;
(*s)->size = strlen(p);
return true;
}
In this version the function takes a pointer to a pointer and doesn't return the string. My other version is this one:
String *init_String(String **s, char *p) {
if (s == NULL) {
return NULL;
}
s->value = p;
s->size = strlen(p);
return s;
}
Which is better for the user? My second question is is it better to malloc according to the user or according to me. In other words should the user malloc a String and then pass it to the init function or should the init function work as alloc_init and do both the call to malloc and the string initialization?
Thanks
Upvotes: 1
Views: 95
Reputation: 249642
How about this?
typedef struct String {
char *value;
size_t size;
int ref; // if nonzero, do not free(value)
} String;
String refer_String(const char *p) {
String out = { p, strlen(p), 1 };
return out;
}
String copy_String(const char *p) {
String out = { strdup(p), strlen(p), 0 };
return out;
}
void free_String(const String *s) {
if (!s->ref) {
free(s->value);
}
}
This provides a way to refer to existing literal strings like your original code, but also a way to create new strings which may be modified.
Upvotes: 3