memchr

Syntax

void *memchr(const void *membuffer, int val, int size)

Arguments

membuffer
The string / memory buffer to search
val
The byte value to search for
size
The size (in bytes) of the memory block to search. Must be equal to or less than the buffer size, or buffer overrun errors can occur.

Return

Returns a memory location pointer to the first occurrence of the given value in the memory block, or NULL if the value is not found.

Description

memchr searches a block of memory for the first occurrence of a given value. It can be used to find the first appearance of a letter in a string. For PHP programmers, memchr is similar to strpos.

Example

// Allocate memory for a string
char *stringbuffer;
stringbuffer = malloc(1000);
sprintf(stringbuffer, "whatever");

// Search for first letter e
char* stringpointer;
stringpointer = memchr(stringbuffer, 'e', strlen(stringbuffer));

// Print everything after first
// letter e if found, or show
// a message if not
if (stringpointer != NULL) {
  // This should print "ever"
  printf("%s", stringpointer);
}
else {
  printf("Character not found.");
}

// Release the memory again
free(stringbuffer);

See Also

sprintf, strncmp, strcmp