How to implement the memchr function in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>

void* memchr(const void* s, int c, size_t n) {
	// find first occurrence of c in s from s[0] to s[n]
	const unsigned char ch = c;
	const unsigned char* p = (const unsigned char*)s;

	for (; 0 < n; p++, n--)
		if (*p == ch)
			return (void*)p;
	return NULL;
}

int main()
{
	char str[32] = "c programming";

	puts(memchr(str, 'm', strlen(str)));

	return 0;
}





/*
run:
         
mming
      
*/


 



answered Dec 16, 2022 by avibootz
edited Dec 16, 2022 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

void* memchr(const void* s, int c, size_t n) {
	// find first occurrence of c in s from s[0] to s[n]
	const unsigned char ch = c;
	const unsigned char* p = (const unsigned char*)s;

	for (; 0 < n; p++, n--)
		if (*p == ch)
			return (void*)p;
	return NULL;
}

int main()
{
	char str[32] = "c programming";

	char* p = memchr(str, 'm', 5);

	if (p != NULL)
		puts(p);
	else
		puts("Not Found");

	return 0;
}





/*
run:
         
Not Found
      
*/

 



answered Dec 16, 2022 by avibootz

Related questions

1 answer 127 views
127 views asked Apr 23, 2023 by avibootz
1 answer 92 views
92 views asked Jun 10, 2025 by avibootz
1 answer 142 views
1 answer 143 views
1 answer 111 views
111 views asked Aug 2, 2024 by avibootz
2 answers 234 views
234 views asked Jan 7, 2024 by avibootz
...