在C中创建我自己的memset函数 [英] create my own memset function in c
问题描述
这是原型:
void *memset(void *s, int c, size_t n)
首先,我不确定是否必须返回某些内容,因为例如当我使用memset时,我会这样做
first im not sure if I have to return something because when I use the memset i do for example
memset(str, 'a', 5);
代替
str = memset(str, 'a', 5);
我的代码在这里:
void *my_memset(void *b, int c, int len)
{
int i;
i = 0;
while(b && len > 0)
{
b = c;
b++;
len--;
}
return(b);
}
int main()
{
char *str;
str = strdup("hello");
my_memset(str, 'a', 5);
printf("%s\n", str);
}
我不想在此函数中使用数组,以便更好地了解指针和内存,因此我没有两件事: -如何将int c复制到我的void b指针上的字符中 -我在使用哪种条件以确保它在'\ 0'字符之前停止
I dont want to use array in this function, to better understand pointer and memory, so I dont get 2 things: - how to copy the int c into a character on my void b pointer - what condition to use on my while to be sure it stop before a '\0' char
我想知道是否有一种方法可以在不强制转换的情况下执行此功能?
edit: i was wondering is there a way to do this function without casting ?
推荐答案
如何将int c复制到我的void b指针上的字符中
how to copy the int c into a character on my void b pointer
您将void指针转换为无符号的char指针:
You convert the void pointer to an unsigned char pointer:
void *my_memset(void *b, int c, int len)
{
int i;
unsigned char *p = b;
i = 0;
while(len > 0)
{
*p = c;
p++;
len--;
}
return(b);
}
我在使用哪种条件以确保其在'\ 0'字符之前停止
what condition to use on my while to be sure it stop before a '\0' char
memset必须信任传入的长度.memset需要在一般的内存上工作,而不仅仅是终止于0的字符串-因此不应进行此类检查.
memset have to trust the length that is passed in. memset needs to work on a general piece of memory, not just a 0 terminated string - so there should not be such a check.
如果您仍然需要检查0字节.你会
If you anyway would need to check for a 0 byte. you'd do
if (*p == 0) //or if(!*p )
break;
这篇关于在C中创建我自己的memset函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!