Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has anyone implemented a replacement for string.h using a struct to store the string and length?

Tags:

c

string

In the C standard library, strings are implemented using an array of chars, terminated by a null character: '\0'. Such ASCIZ strings lead to inefficiency because every time we need to know the length of a string, we need to iterate over it looking for '\0'.

The way around this is to store the length of the string when we create it, e.g. using a struct as follows:

typedef struct cstring_ {
    size_t nchars;
    char chars[0];
} cstring;

Has anyone made a shared library implementing the string.h functions, but using a struct instead of char * to pass strings around?

If not, is there a specific reason why this would be a bad idea?

like image 426
j b Avatar asked Aug 31 '25 23:08

j b


1 Answers

There are probably dozens of those. Have a look at Glib's GString for example.

like image 55
Mat Avatar answered Sep 03 '25 11:09

Mat