memchr
函数功能
在给定的内存块中查找首次出现的指定字符。该函数返回指向内存中找到字符的指针,若未找到则返回NULL。
函数定义
void *memchr(const void *ptr, int value, size_t num);
参数说明
参数名 |
描述 |
取值范围 |
输入/输出 |
---|---|---|---|
ptr |
指向内存区域的指针,搜索将在此内存区域进行。 |
非空指针,指向有效内存,至少有num字节可访问。 |
输入 |
value |
要查找的字符,传入的值会转换为unsigned char类型。 |
0-255,超出部分会被截断 |
输入 |
num |
要查找的字节数。 |
非负数,不超过实际内存大小。 |
输入 |
返回值
- 成功:如果找到了字符,返回指向该字符的指针。
- 失败:对标开源Glibc,不返回特殊异常值。

查找是逐字节的,严格检查num个字节,不管中间是否有空字符,即它查找value在内存中的位置,与strchr不同。
示例
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello, World!"; char *result; result = memchr(str, 'o', sizeof(str)); if (result != NULL) { printf("Found 'o' at index: %ld\n", (long)(result - str)); } else { printf("Did not find 'o'\n"); } result = memchr(str, 'x', sizeof(str)); if (result != NULL) { printf("Found 'x' at index: %ld\n", (long)(result - str)); } else { printf("Did not find 'x'\n"); } return 0; }
运行结果:
Found 'o' at index: 4 Did not find 'x'
父主题: 函数定义