标题: memchr函数实现及简单使用 [打印本页]

作者: xiaojuan    时间: 2014-9-24 22:36
标题: memchr函数实现及简单使用

//:Vc++6.0  String  memchr函数
//功能:查找里面第一个和目标字符匹配的字符
//参数:ptr 首地址  value 想要查找的字符值   num 查到那个地址
//返回值:如果成功,返回指向字符的指针;否则返回NULL
#include<stdio.h>

const void *memchr (const void *ptr, int value, int num);

int main(void)
{
char * pch;
char str[] = "hello world";
pch = (char*) memchr (str, 'e', 12);
if (pch!=NULL)
printf ("'e' found at position %d.\n", pch - str + 1);
else
printf ("'e' not found.\n");

return 0;
}

const void *memchr (const void *ptr, int value, int num)
{
if (ptr == NULL)
{
perror("ptr");
return NULL;
}
char * p = (char *)ptr;
while (num--)
{
if (*p != (char)value)
p++;
else
return p;
}

return NULL;
}

//在vc++6.0中的运行结果为:'e' found at position 2.
//注:在VC++6.0中函数只能比较字符串//:~







欢迎光临 (http://www.51hei.com/bbs/) Powered by Discuz! X3.1