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

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

The way around this is to preserve the length of the string when creating it, for example. using the following structure:

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

Has anyone created a shared library that implements string.h functions, but using struct instead char *to pass strings around?

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

+3
source share
7 answers

, , . Glib GString, .

+5

- , string.h, struct char *, ?

.

11 , C: < string.h > , , , .

( ++ std::string).

, ?

, : , API, , , , . , , . .

, , , , , .

, .

Mat GLib GString.

Windows, Microsoft BSTR ( ++ bstr_t) : const char *, SysAllocString , SysFreeString ..

, .

+3

>

, : "" chumminess C ", , C , , , . (, .)

, char chars[1];.

+1

, , Glib, BString, VStr . , , , , , API- . (++ std::string , , ++.)

strlen, "" memcpy . , .

+1

- ( struct). . , , .

0

, , , , . , NULL.

, : , , ?

0

I don't think this is a bad idea, in fact the implementation of the string in C ++ is the same as you said. And there is also an implementation of c, such as gstring in glib. This is almost the standard library in the Linux world. I think the reason this is not standard c lib is because c lang has a too long history and most developers and projects are used for the orignal c style string.

0
source

All Articles