C 中 "size_t" 的等价物是什么?
What is the equivalent of "size_t" in C?
假设我想做一个像
这样的函数
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;
}
但我想让它尽可能可靠。例如,以上仅在保证最大 int
大于或等于字符数组的最大大小时才有效。我怎样才能用纯 C 覆盖我的所有基础?
使用指针。
您将始终能够 return 指向数组中有效元素的指针。未找到条件由 returning NULL 表示。
不,认真的。 size_t
是标准的 C 类型。它在 <stddef.h>
.
中定义
(这是 "What is the equivalent of “size_t” in C?" 的答案)
对于您所写的确切功能,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
}
因此,一般来说,如果您想在用户提供的数组中查找某些内容,return使用指针在 C 中是最惯用的。
你可以returnssize_t
(包括size_t
和-1
的所有可能值),但是它不是标准的 C,所以我不推荐它。我只是为了完整性才提到它。
将您的问题解释为:
How to not rely in index size for pointer arithmetic?
答案是:
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
char *aux = str;
while (*aux != c )
{
if (*aux == '[=10=]')
return -1;
aux++;
}
return aux - str;
}
假设我想做一个像
这样的函数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;
}
但我想让它尽可能可靠。例如,以上仅在保证最大 int
大于或等于字符数组的最大大小时才有效。我怎样才能用纯 C 覆盖我的所有基础?
使用指针。
您将始终能够 return 指向数组中有效元素的指针。未找到条件由 returning NULL 表示。
不,认真的。 size_t
是标准的 C 类型。它在 <stddef.h>
.
(这是 "What is the equivalent of “size_t” in C?" 的答案)
对于您所写的确切功能,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
}
因此,一般来说,如果您想在用户提供的数组中查找某些内容,return使用指针在 C 中是最惯用的。
你可以returnssize_t
(包括size_t
和-1
的所有可能值),但是它不是标准的 C,所以我不推荐它。我只是为了完整性才提到它。
将您的问题解释为:
How to not rely in index size for pointer arithmetic?
答案是:
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
char *aux = str;
while (*aux != c )
{
if (*aux == '[=10=]')
return -1;
aux++;
}
return aux - str;
}