atoi、itoa
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>
int myatoi(const char * str)
{
int i = 0;
int tmp = 0;
int flag = 1;
assert(str != NULL);
//如果是前面有空格先消去
while (isspace(*str)){ //用函数isspace判断是否为空白字符
str++;
}
if(*str == '-'){
flag = -1;
str++;
}
while(*str != '\0'){
if(*str > 57 || *str < 48) return -1;
str++;
i++;
}
if(i != 0){
str -= i;
}
while(*str != '\0'){
tmp = tmp*10+(*str -'0');//0-48
str++;
i++;
}
return tmp*flag;
}
void myitoa(int n,char *str)
{
char *head = str;
char ch;
int i=0,j=0;
while(n != 0){
*str = n%10 +'0';
n /= 10;
j++;
str++;
}
str--;
while(head < str){
ch = *head;
*head++ = *str;
*str-- = ch;
i++;
}
//printf("head %s\n",head);
//printf("str %s\n",str);
str += i+1;
*str = '\0';
}
int main()
{
int i;
char *c = " -123456";
char *k = NULL;
char *m = "dfdfg";
i = myatoi(m);
printf("%d\n",i);
int b = 123456789;
char str[32];
myitoa(b,str);
printf("%s\n",str);
return 0;
}
memcpy
void *mymemcpy(void *dest, const void *src, int count)
{
void *ptr = dest;
if (NULL == dest || NULL == src || count <= 0)
return NULL;
while (count--)
*(char *)dest++ = *(char *)src++;
return ptr;
}
由于拷贝是从低地址开始,按字节进行拷贝的,需要考虑内存重叠:
void *memcpy(void *dest, const void *src,size_t n)
{
if(dest==NULL||src==NULL)
return NULL;
void *res = dest;
if(dest<=src||(char*)dest>=(char*)src+n){
while(n--){
//从低地址开始复制
*(char*)dest =*(char*)src;
dest=(char*)dest+1;
src=(char*)src+1;
}
}
else{
//从高地址开始复制
src = (char*)src + n -1;
dst = (char*)dst + n -1;
while(n--){
*(char*)dst = *(char*)src;
dst = (char*)dst -1;
src = (char*)src -1;
}
}
return res;
}
|