memchr() function in C++

In this guide, you will learn what is memchr() function is in C++ programming and how to use it with an example.

1. memchr() Function Overview

The memchr() function in C++ is used to search for the first occurrence of a character in a block of memory. This function is part of the C++ <cstring> header and operates on binary data, not just textual strings. The function searches the first n bytes of the memory area pointed to by src for the character c.

Signature:

void* memchr(const void* src, int c, size_t n);

Parameters:

- src: Pointer to the memory block where the search is performed.

- c: The character to be searched. It is passed as its int promotion, but it's internally converted back to unsigned char.

- n: Number of bytes to be analyzed in the memory block.

2. Source Code Example

#include <iostream>
#include <cstring>

int main() {
    const char str[] = "C++Programming";

    // Search for the first occurrence of 'P' in the string
    char* result = (char*) memchr(str, 'P', strlen(str));

    if (result) {
        std::cout << "Character 'P' found at position: " << (result - str) << std::endl;
    } else {
        std::cout << "Character 'P' not found." << std::endl;
    }

    return 0;
}

Output:

Character 'P' found at position: 3

3. Explanation

In the provided source code:

1. The necessary header files are included: <iostream> for input/output operations and <cstring> for memchr() and strlen().

2. We've defined a constant character array named str.

3. The memchr() function is used to find the first occurrence of the character 'P' in the string.

4. If the character is found, the position is printed; otherwise, a not-found message is displayed.

5. The position is calculated by subtracting the start address of str from the pointer result.


Comments