how to make a not null-terminated c string?

前端 未结 7 1058
無奈伤痛
無奈伤痛 2020-12-19 07:18

i am wondering :char *cs = .....;what will happen to strlen() and printf(\"%s\",cs) if cs point to memory block which is huge but with no \'\\0\' in it? i write these lines

相关标签:
7条回答
  • 2020-12-19 08:07

    A "C string" is, by definition, null-terminated. The name comes from the C convention of having null-terminated strings. If you want something else, it's not a C string.

    So if you have a string that is not null-terminated, you cannot use the C string manipulation routines on it. You can't use strlen, strcpy or strcat. Basically, any function that takes a char* but no separate length is not usable.

    Then what can you do? If you have a string that is not null-terminated, you will have the length separately. (If you don't, you're screwed. You need some way to find the length, either by a terminator or by storing it separately.) What you can do is allocate a buffer of the appropriate size, copy the string over, and append a null. Or you can write your own set of string manipulation functions that work with pointer and length. In C++ you can use std::string's constructor that takes a char* and a length; that one doesn't need the terminator.

    0 讨论(0)
提交回复
热议问题