Why are C#/.Net strings length-prefixed and null terminated?

前端 未结 5 800
名媛妹妹
名媛妹妹 2021-02-12 12:34

After reading What's the rationale for null terminated strings? and some similar questions I have found that in C#/.Net strings are, internally, both length-prefixed and nul

5条回答
  •  醉梦人生
    2021-02-12 13:25

    While the length field makes it easy for the framework to determine the length of a string (and it lets string contain characters with a zero value), there's an awful lot of stuff that the framework (or user programs) need to deal with that expect NULL terminated strings.

    Like the Win32 API, for example.

    So it's convenient to keep a NULL terminator on at the end of the string data because it's likely going to need to be there quite often anyway.

    Note that C++'s std::string class is implemented the same way (in MSVC anyway). For the same reason, I'm sure (c_str() is often used to pass a std::string to something that wants a C-style string).

提交回复
热议问题