<分区>
Possible Duplicate:
Different answers from strlen and sizeof for Pointer & Array based init of String
谁能帮我理解 C 编程中 sizeof 方法和 strlen 方法的区别?
标签 c
<分区>
Possible Duplicate:
Different answers from strlen and sizeof for Pointer & Array based init of String
谁能帮我理解 C 编程中 sizeof 方法和 strlen 方法的区别?
最佳答案
strlen()
用于获取存储在数组中的字符串的长度。
sizeof()
用于获取任何类型数据的实际大小(以字节为单位)。
此外,sizeof()
是一个编译时表达式,它为您提供类型或变量类型的大小。它不关心变量的值。
strlen() 是一个函数,它接受一个指向字符的指针,并从这个字符开始遍历内存,寻找一个空字符。它在找到空字符之前计算字符数。换句话说,它为您提供了 C 风格的空终止字符串的长度。
两者完全不同。在 C++ 中,你不需要太多,strlen() 用于 C 风格的字符串,应该用 C++ 风格的 std::strings
代替,而 sizeof 的主要应用()
在 C 中作为函数的参数,如 malloc()
、memcpy()
或 memset()
,所有你不应该在 C++ 中使用它(使用 new、std::copy()
和 std::fill()
或 constructors
) .
关于c - c语言中sizeof和strlen的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8590332/