字符串(字符数组)可以在 C 中修改,但不能修改字符串文字。但是为什么像 strlen(const char *str) 这样的字符串函数有一个指向常量字符的指针呢?
最佳答案
因为他们不修改(也不需要修改)他们的参数字符串。这就是 const
的意思。
如果 strlen
的参数声明为 char *
(没有 const
),您将无法使用 strlen
确定常量字符串的长度。例如
size_t my_own_strlen(char *str) { /* whatever */ }
const char hello[] = "Hello";
size_t l1 = my_own_strlen(hello); // Error: cannot convert `const char *` to `char *`
size_t l2 = strlen(hello); // OK
将该参数声明为 const char *
使得 strlen
适用于常量和非常量字符串。
关于c - 为什么字符串函数有一些参数作为 const char *(指向常量字符的指针)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39967934/