Chinaunix首页 | 论坛 | 博客
  • 博客访问: 282603
  • 博文数量: 87
  • 博客积分: 1206
  • 博客等级: 少尉
  • 技术积分: 725
  • 用 户 组: 普通用户
  • 注册时间: 2010-08-16 00:12
个人简介

do the right things the right ways

文章分类

全部博文(87)

文章存档

2017年(5)

2016年(6)

2015年(1)

2012年(11)

2011年(64)

分类: C/C++

2011-03-23 13:27:42

#include
#include

typedef unsigned int size_t;
typedef char u8;

size_t my_strlen(const char *str)
{
size_t len = 0;

while (*str)
{
len++;
str++;
}

return len;
}

char *my_strcpy(char *pdst, const char *psrc)
{
printf("@%s()\n", __func__);
while ((*pdst++ = *psrc++));

return pdst;
}

int my_strcmp(const char *s1, const char *s2)
{
printf("@%s()\n", __func__);
while (*s1 == *s2)
{
if ('\0' == *s1)
{
return 0;
}

s1++;
s2++;
}

return *s1 - *s2;
}

void *my_memcpy(void *pdst, const void *psrc, size_t num)
{
u8 *pd;
const u8 *ps;

pd = pdst;
ps = psrc;

printf("@%s()\n", __func__);
while (num > 0)
{
//*(char *)pdst++ = *ps++;
*pd++ = *ps++;

num--;
}

return pdst;
}

void *my_memset(void *buff, int c, size_t size_num)
{
size_t i;
char *ps = buff;

printf("@%s()\n", __func__);
for (i = 0; i < size_num; i++)
{
((char *)buff)[i] = c;
//*ps = c;
//ps++;
}

return buff;
}

int main(int argc, char *argv[])
{
const char *str = "hello";
char *cpto;
size_t len;
int i;
const char *str1 = "abc";
const char *str2 = "acb";

//memcpy
len = 3;
cpto = (char *)malloc(len);
my_memcpy(cpto, str, len);
printf("str = %s\n", cpto);
//strcpy
cpto = (char *)malloc(my_strlen(str));
my_strcpy(cpto, str);
printf("str = %s\n", cpto);
//strcmp
i = my_strcmp(str1, str2);
printf("The compare result is : %d\n", i);

//memset
//cpto = (unsigned char *)malloc(len * sizeof(int));
my_memset(cpto, 127, len);
for (i = 0; i < len; i++)
{
printf("%d\n", cpto[i]);
}

return 0;
}
阅读(795) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

spanthrive2011-03-24 00:24:18

多谢指点

GFree_Wind2011-03-24 00:05:21

给你一个建议,可以去看看c库中的实现。你可以发现C库中如何提高效率的。比如字符串复制,可以4字节一起复制(32位机),等等。