Why null-terminated strings? Or: null-terminated vs. characters + length storage

后端 未结 10 1294
-上瘾入骨i
-上瘾入骨i 2020-12-23 17:29

I\'m writing a language interpreter in C, and my string type contains a length attribute, like so:

struct String
{
    char* charac         


        
10条回答
  •  一向
    一向 (楼主)
    2020-12-23 17:29

    You're absolutely right that 0-termination is a method which is poor with respect to type checking and performance for part of the operations. The answers on this page already summarize the origins and uses for it.

    I liked the way Delphi stored strings. I believe it maintains a length/maxlength in before the (variable length) string. This way the strings can be null-terminated for compatibility.

    My concerns with your mechanism: - additional pointer - immutability si in the core parts of your language; normally string types are not immutable so if you ever reconsider than it'll be tough. You'd need to implement a 'create copy on change' mechanism - use of malloc (hardly efficient, but may be included here just for ease?)

    Good luck; writing your own interpreter can be very educational in understanding mainly the grammar and syntax of programming languages! (at least, it ws for me)

提交回复
热议问题