C Language: memchr function
(Search Memory Block for Character)
In the C Programming Language, the memchr function searches within the first n characters of the object pointed to by s for the character c. It returns a pointer to it.
Syntax
The syntax for the memchr function in the C Language is:
void *memchr(const void *s, int c, size_t n);
Parameters or Arguments
- s
- A pointer to a string where the search will be performed.
- c
- The value to be found.
- n
- The number of characters to search within the object pointed to by s.
Returns
The memchr function returns a pointer to the first occurrence of the character c within the first n characters of the object pointed to by s. If c isn't found, it returns a null pointer.
Required Header
In the C Language, the required header for the memchr function is:
#include <string.h>
Applies To
In the C Language, the memchr function can be used in the following versions:
- ANSI/ISO 9899-1990
memchr Example
Let's look at an example to see how you would use the memchr function in a C program:
/* Example using memchr by TechOnTheNet.com */ #include <stdio.h> #include <string.h> int main(int argc, const char * argv[]) { char search[] = "TechOnTheNet"; char *ptr; /* Return a pointer to the first 'N' within the search string */ ptr = (char*)memchr(search, 'N', strlen(search)); /* If 'N' was found, print its location (This should produce "10") */ if (ptr != NULL) printf("Found 'N' at position %ld.\n", 1+(ptr-search)); else printf("'N' was not found.\n"); return 0; }
When compiled and run, this application will output:
Found 'N' at position 10.
Similar Functions
Other C functions that are similar to the memchr function:
See Also
Other C functions that are noteworthy when dealing with the memchr function:
Advertisements