在任何实现中,以下内容始终正确吗?
(strlen("some string with weird characters") + 1) * sizeof(char)
== sizeof("some string with weird characters");
Run Code Online (Sandbox Code Playgroud)
我问我是否可以可靠地用于(strlen(my_string) + 1) * sizeof(char)计算任何字符串的二进制大小。另外,请告诉我是否有更好的方法。
否。唯一不同的情况是嵌入的null:
(strlen("strlen can see this\0strlen cannot see this") + 1) * sizeof(char)
!= sizeof("strlen can see this\0strlen cannot see this");
Run Code Online (Sandbox Code Playgroud)
另外,sizeof(char)始终是1,因此没有意义。
由于字符串文字是类型的数组char[N](对于某个正数size N),因此该sizeof方法是获取其大小的正确方法(但/ sizeof(char)实际上是不必要的1)。