---
title: memchr
description: "在给定的内存块中查找首次出现的指定字符。该函数返回指向内存中找到字符的指针，若未找到则返回NULL。"
url: https://www.hikunpeng.com/document/detail/zh/kunpengboostkithistory/252RC1/accel/kunpengaccel_ksl_16_0206.html
sourcePath: /source/zh/kunpengboostkithistory/252RC1/accel/kunpengaccel_ksl_16_0206.html
indexId: 5aab189ed4016dc1218b4c2a7f1c5c3e9785e0f5eaaf107a430411d225fb0ce976
---
# 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 = (char *)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 = (char *)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'
```
