memchr() Function
The memchr()
function in C is used to search through a block of memory for the first occurrence of a specified byte. It examines the memory one byte at a time, treating each as an unsigned character, and returns a pointer to the matching byte if found, or a null pointer if the byte is not present.
Syntax of memchr()
</>
Copy
const void *memchr(const void *ptr, int value, size_t num);
void *memchr(void *ptr, int value, size_t num);
Parameters
Parameter | Description |
---|---|
ptr | Pointer to the block of memory to be searched. |
value | The byte value to be located. Although passed as an int, it is used as an unsigned char for the search. |
num | The number of bytes to be examined in the memory block. |
It is important to note that both the specified value and each byte in the memory block are interpreted as unsigned characters, ensuring that the search is performed accurately even when dealing with binary data.
Examples for memchr()
Example 1: Searching for a Character in a String
This example demonstrates how to use memchr()
to locate a specific character within a string.
Program
</>
Copy
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *result = memchr(str, 'W', strlen(str));
if (result != NULL) {
printf("Character found: %c\n", *result);
} else {
printf("Character not found.\n");
}
return 0;
}
Explanation:
- A string
str
is initialized with the value"Hello, World!"
. - The
memchr()
function searches the string for the character'W'
within the length of the string. - If the character is found, a pointer to its location is returned and the character is printed.
- If the character is not found, a message indicating the absence of the character is displayed.
Output:
Character found: W
Example 2: Searching for a Non-Existent Character
This example demonstrates the behavior of memchr()
when the specified character is not present in the memory block.
Program
</>
Copy
#include <stdio.h>
#include <string.h>
int main() {
char buffer[] = "Example buffer data";
char *result = memchr(buffer, 'z', sizeof(buffer));
if (result != NULL) {
printf("Character found: %c\n", *result);
} else {
printf("Character not found.\n");
}
return 0;
}
Explanation:
- A character array
buffer
is initialized with the string"Example buffer data"
. - The
memchr()
function is used to search for the character'z'
within the entire buffer. - Since the character
'z'
is not present, the function returns a null pointer. - A message is printed to indicate that the character was not found.
Output:
Character not found.