Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

memchr — C23 generic byte search

The C23 generic function `memchr(s, c, n)` from `<string.h>` finds the first byte equal to `c` after conversion to `unsigned char` among the first `n` bytes of the object at `s`. It returns a pointer exactly to the first match or null; the implementation must behave as if it reads sequentially and stops immediately on a match.

Version: C23

Syntax

QVoid *memchr(QVoid *s, int c, size_t n);

The C23 generic function memchr(s, c, n) from <string.h> finds the first byte equal to c after conversion to unsigned char among the first n bytes of the object at s. It returns a pointer exactly to the first match or null; the implementation must behave as if it reads sequentially and stops immediately on a match.

The example searches a four-byte array containing two 0x42 bytes. The real call returns the first occurrence, so the pointer difference and byte read produce 1 42 rather than merely printing a Boolean.

memchr does not search for a terminator and can inspect binary data containing zero bytes, but n must not extend beyond the accessible object; even for n == 0, C23 still requires a valid pointer value. C23 preserves the searched array’s const qualification in the result type and does not accept volatile or restrict element qualification here; suppressing a possible macro exposes the concrete external function, but that use is obsolescent.

Examples

#include <stddef.h>
#include <stdio.h>
#include <string.h>
int main(void){const unsigned char data[]={0x10,0x42,0x42,0x20};const unsigned char *hit=memchr(data,0x42,sizeof data);printf("%td %02X\n",hit-data,(unsigned)*hit);return 0;}

Result

1 42

The example searches a four-byte array containing two `0x42` bytes. The real call returns the first occurrence, so the pointer difference and byte read produce `1 42` rather than merely printing a Boolean.

Sources