I’ve googled quite a bit, but I can’t find information on how variable-length strings are generally implemented in higher-level languages. I’m creating my own such language, and am not sure where to start with strings.
I have a struct describing the string
type, and then a create
function that allocates such a ‘string’:
/* A safer `strcpy()`, using `strncpy()` and `sizeof()` */
#define STRCPY(TO, FROM) \
strncpy(TO, FROM, sizeof(TO)); TO[sizeof(TO) - 1] = '\0'
struct string {
// …
char native[1024];
};
string String__create(char native[]) {
string this = malloc(sizeof(struct string));
// …
STRCPY(this->native, native);
return this;
}
However, that would only allow 1kb-long strings. That’s sort of silly, and a huge waste of memory in most cases.
Given that I have to declare the memory to be used somehow… how do I go about implementing a string that can (efficiently) store an (effectively) unbounded number of characters?