标签:des style blog color os art
1.memcpy函数的原型:
void* memcpy(void* dest,cosnt void* src,size_t n);
返回值:返回dest;
功能:从源内存地址src拷贝n个字节到dest内存地址.
这里必须要求源地址的内存和目标地址的内存没有覆盖,如果有覆盖结果是未定义的.
#include <stdio.h> #include <assert.h> void* my_memcpy(void* dest,const void* src,size_t n) { assert(dest != NULL && src != NULL && n > 0); char* dest_t = (char*)dest; const char* src_t = (char*)src; while(n--) *dest_t++ = *src_t++; return dest; } int main(void) { char str[] = "abcedf"; char buf[20] = "aaaaaaaa"; my_memcpy(str,buf,sizeof(str)); printf("%s\n",(char*)str); return 0; }
2.memmove的原型:
void* memmove(void* dest,const void* src,size_t n);
和memcpy的功能差不多,只是多了一层考虑内存有覆盖的情况.
如果dest比src小,就从低地址开始拷贝.
如果dest比src大,就从高地址开始拷贝.
如果dest和src一样,就不拷贝.
#include <stdio.h> void* my_memmove(void* dest,const void* src,size_t n) { char* d = (char*)dest; const char* s = (char*)src; if( d < s) //start copying at begining while dest is little { while(n--) *d++ = *s++; } else if(d > s) //start copying at end while dest is bigger { d += n - 1; s += n - 1; while(n--) *d-- = *s--; } return dest; }
3.atoi的原型:
int my_atoi(char* pstr)
功能:将字符串转换成整型数;atoi()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负号
才开始做转换,而遇到非数字或字符‘\0‘结束转换,并将结果返回.(返回转换后的整型数);
#include <stdio.h> #include <assert.h> int my_atoi(char* pstr) { assert(pstr != NULL); int res = 0; int sign = 1; while(*pstr == ‘ ‘|| *pstr == ‘\t‘) pstr++; sign = (*pstr == ‘-‘? -1 : 1); /*求得符号位置*/ if(*pstr == ‘-‘ || *pstr == ‘+‘) /*跳过符号位置*/ pstr++; while(*pstr != ‘\0‘ && *pstr >= ‘0‘ && *pstr <= ‘9‘) { res = *pstr - ‘0‘ + res*10; pstr++; } return sign*res; /*返回带符号的值*/ } int main(void) { char a[] = "-110000"; char b[] = " 456"; int c = 0; c = my_atoi(a); printf("%d\n",c); c = my_atoi(b); printf("%d\n",c); return 0; }
4.itoa的原型:
c/c++面试题(8)memcopy/memmove/atoi/itoa,布布扣,bubuko.com
c/c++面试题(8)memcopy/memmove/atoi/itoa
标签:des style blog color os art
原文地址:http://www.cnblogs.com/yasanlun/p/3842523.html