以下是否在任何实现中总是正确的?
(strlen("some string with weird characters") + 1) * sizeof(char)
== sizeof("some string with weird characters");
我在问我是否可以可靠地使用 (strlen(my_string) + 1) * sizeof(char)
来计算任何字符串的二进制大小。另外,如果有更好的方法,请告诉我。
最佳答案
没有。唯一不同的是嵌入的空值:
(strlen("strlen can see this\0strlen cannot see this") + 1) * sizeof(char)
!= sizeof("strlen can see this\0strlen cannot see this");
此外,sizeof(char)
始终为 1
,因此没有意义。
由于字符串字面量是 char[N]
类型的数组(对于一些正大小 N
),sizeof
方法是正确的方法获取它们的大小(但是 /sizeof(char)
是不必要的,因为它是 1
)。
关于c - strlen 乘以 sizeof(char) 是否总是等于 sizeof(literal)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55817270/