在 C 语言中谈论字符串时,您实质上是在谈论由 nil 字符 ('\0') 终止的 char 数组。因此,字符串的长度为:
size_t len(const char *s) {
// if no string was passed (null pointer), just return
if (s == NULL)
return 0;
size_t ln;
// iterate over string until you encounter the terminating char
for (ln=0;s[ln] != '\0'; ln++);
return ln;
}
正如@chux-ReinstateMonica 所指出的:这里返回的正确类型是size_t,如果您想避免潜在的溢出问题+ 您正在寻找@ 中strlen() 函数的直接替代品987654327@。毕竟,字符串的长度永远不会是负数,因此使用无符号的size_t 比有符号的int 更有意义。
现在这显然假设输入是一个有效的字符串。如果我要这样做:
int main( void ) {
char * random = malloc(1024); // allocate 1k chars, without initialising memory
printf("length is: %zu\n", len(random)); // use %zu because size_t is unsigned!
return 0;
}
无法保证我分配的内存甚至包含终止字符,因此函数返回大于 1024 的值并非不可能。类似的情况也是如此:
char foo[3] = {'f', 'o', 'o'}; // full array, no terminating char
这个字符串在内存中可能看起来像这样:
//the string - random memory after the array
| f | o | o | g | a | r | b | a | g | e | U | B | \0 |
使它看起来像一个 12 个字符的字符串。如果您随后使用假定的 12 长度来写入实际数组,则所有赌注都将关闭(未定义的行为)。
这个字符串应该是:
char foo[4] = {'f', 'o', 'o', '\0'}; // or char[4] foo = "foo";
您可以阅读我在其他地方给出的旧答案,了解有关如何获取传递给函数 here 的字符串长度的更多详细信息