memchr() function in C++

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

1.memchr() Function Overview

Thememchr() 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 firstn bytes of the memory area pointed to bysrc for the characterc.

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> formemchr() andstrlen().

2. We've defined a constant character array namedstr.

3. Thememchr() 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 ofstr from the pointerresult.


Comments