这是一个奇怪的问题。这个功能可以更安全吗?寻找提示和你的想法!
我写了一个C函数。它的'像'strchr/strrchr。它应该在c字符串中寻找一个字符,但是要倒退,并返回一个指向它的指针。由于c字符串不是“空启动的”,它还需要第三个参数“count”,表示它应该向后看的字符数。
/*
*s: Position from where to start looking for the desired character.
*c: Character to look for.
*count: Amount of tests to be done
*
* Returns NULL if c is not in (s-count,s)
* Returns a pointer to the occurrence of c in s.
*/
char* b_strchr(const char* s,int c,size_t count){
while (count-->0){
if (*s==c) return s;
s--;
}
return NULL;
}
我已经做它的一些测试,但 你看到它的任何缺陷?安全问题还是如此?任何增强功能?可以改进吗? 更重要的是:这是一个坏主意吗?
一些用法。
char* string = "1234567890";
printf("c: %c\n",*b_strchr(string+9,'5',10));//prints 5
printf("c: %c\n",*b_strchr(string+6,'1',7));//prints 1
编辑:新界面,一些变化。
/*
* from: Pointer to character where to start going back.
* begin: Pointer to characther where search will end.
*
* Returns NULL if c is not between [begin,from]
* Otherwise, returns pointer to c.
*/
char* b_strchr(const char* begin,int c,const char* from){
while (begin<=from){
if (*from==c) return from;
from--;
}
return NULL;
}
谢谢!没有想过这件事。 – Tom 2009-07-03 02:48:59