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 116 views
116 views asked Apr 23, 2023 by avibootz
1 answer 85 views
85 views asked Jun 10, 2025 by avibootz
1 answer 132 views
1 answer 128 views
1 answer 100 views
100 views asked Aug 2, 2024 by avibootz
2 answers 213 views
213 views asked Jan 7, 2024 by avibootz
...