我要评分
获取效率
正确性
完整性
易理解

memchr

Function Usage

Searches for a character that appears for the first time in a specified memory block, and returns a pointer to the character found in the memory. If the character is not found, NULL is returned.

Function Syntax

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

Parameters

Parameter

Description

Value Range

Input/Output

ptr

Pointer to a memory block within which the search is performed.

Non-null pointer to a valid memory block, with at least num bytes accessible.

Input

value

Character to be searched for. The input value is converted to the unsigned char type.

0 to 255. The excess part will be truncated.

Input

num

Number of bytes to be searched for.

Non-negative number that does not exceed the memory size.

Input

Return Value

  • Success: A pointer to the found character is returned.
  • Failure: See those of open source glibc. No other exception values will be returned.

Different from strchr, memchr scans num bytes (byte by byte) regardless of whether there is a null character. That is, it searches for the position of value in the memory.

Example

#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;
}

Output:

Found 'o' at index: 4
Did not find 'x'