c - strlen 乘以 sizeof(char) 是否总是等于 sizeof(literal)?

标签 c string byte

以下是否在任何实现中总是正确的?

(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/

相关文章:

c++ - 确定文件 HANDLE 是否为管道句柄

python - 如何在 Python 中将文件加载为 List 类型?

arrays - 如何迭代两个 byte slice

c - 持有空值的变量是否也占用内存中的空间?

python - 如何在Python中将十进制数转换为字节列表

c - 链表,删除尾函数

c - C中fprintf的间距

c - listen() 积压上限

c - 使字符串的行数等于变量的值

javascript - 无法在 Facebox 中使用 Facebook 多好友选择器