memchr()

Searches for an occurrence of a character.

  #include <string.h>
  
  void *memchr(const void *s, int c, size_t n);    
Parameter

s

The memory to search

c

The character to search for.

n

The maximum length to search.

Remarks

This function looks for the first occurrence of c in the first n characters of the memory area pointed to by s.

The function returns a pointer to the found character, or a null pointer ( NULL) if c cannot be found.

This facility may not be available on some configurations of the EWL.

Listing: Example of memchr() usage

#include <string.h>

#include <stdio.h>

#define ARRAYSIZE 100

int main(void)

{

/* s1 must by same length as s2 for this example! */

char s1[ARRAYSIZE] = "laugh* giggle 231!";

char s2[ARRAYSIZE] = "grunt sigh# snort!";

char dest[ARRAYSIZE];

char *strptr;

int len1, len2, lendest;

/* Clear destination string using memset(). */

memset(dest, '\0', ARRAYSIZE);

/* String lengths are needed by the mem functions. */

/* Add 1 to include the terminating '\0' character. */

len1 = strlen(s1) + 1;

len2 = strlen(s2) + 1;

lendest = strlen(dest) + 1;

printf(" s1=%s\n s2=%s\n dest=%s\n\n", s1, s2, dest);

if (memcmp(s1, s2, len1) > 0)

memcpy(dest, s1, len1);

else

memcpy(dest, s2, len2);

printf(" s1=%s\n s2=%s\n dest=%s\n\n", s1, s2, dest);

/* Copy s1 onto itself using memchr() and memmove(). */

strptr = (char *)memchr(s1, '*', len1);

memmove(strptr, s1, len1);

printf(" s1=%s\n s2=%s\n dest=%s\n\n", s1, s2, dest);

return 0;

}

Output:

s1=laugh* giggle 231!

s2=grunt sigh# snort!

dest=

s1=laugh* giggle 231!

s2=grunt sigh# snort!

dest=laugh* giggle 231!

s1=laughlaugh* giggle 231!

s2=grunt sigh# snort!

dest=laugh* giggle 231!