假设我想做一个像这样的函数
int indexOf ( char * str, char c )
{
// returns the index of the chracter c in the string str
// returns -1 if c is not a character of str
int k = 0;
while (*str)
{
if (*str == c) break;
else ++str;
}
return *str ? k : -1;
}
Run Code Online (Sandbox Code Playgroud)
但我希望尽可能让它变得可靠.例如,只有在int保证最大值大于或等于字符数组的最大大小时,上述方法才有效.如何在纯C中覆盖我的所有基础?
不,真的.size_t是标准的C类型.它的定义是<stddef.h>.
(这就是"C中相当于"size_t"的答案?")
对于你写的确切函数,strchr会更合适 - 调用者可以像这样使用它:
const char* str = "Find me!find mE";
char* pos = strchr(str, '!');
if(pos) // found the char
{
size_t index = (pos - str); // get the index
// do the other things
}
else
{
// char not found
}
Run Code Online (Sandbox Code Playgroud)
所以,一般来说,如果你想在用户提供的数组中找到一些东西,那么返回一个指针在C语言中是最惯用的.
你可以返回ssize_t(其中包括所有可能的值size_t,和-1),但它不是标准的C,所以我不建议这样做.我只是提到完整性.