how to make a not null-terminated c string?

前端 未结 7 1050
無奈伤痛
無奈伤痛 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 07:47

    If it's not null-terminated, then it's not a C string, and you can't use functions like strlen - they will march off the end of the array, causing undefined behaviour. You'll need to keep track of the length some other way.

    You can still print a non-terminated character array with printf, as long as you give the length:

    printf("str is %.3s",s2);
    printf("str is %.*s",s2_length,s2);
    

    or, if you have access to the array itself, not a pointer:

    printf("str is %.*s", (int)(sizeof s2), s2);
    

    You've also tagged the question C++: in that language, you usually want to avoid all this error-prone malarkey and use std::string instead.

提交回复
热议问题