zoukankan      html  css  js  c++  java
  • C/C++自实现的函数(memset, memcpy, atoi)

    函数原型:

    void * memset ( void * buffer, int c, size_t num );

      关于void * 因为任何类型的指针都可以传入memset函数,这也真是体现了内存操作函数的意义,因为他操作的对象仅仅是一片内存,而不论这片内存是什么类型!

      void无类型,其实是一种类型上的抽象,它可以转换成任何类型!

    void *myMemset(void *s, int ch, size_t n)  // point 1: s的类型未知,n代表字节数 
    {
        assert(NULL != s);
        void *tmp = s;
        while(n --){
            *(char *)tmp = (char)ch; //point 2: 将tmp转成char类型占用1个字节来赋值成c
            tmp = (char *)tmp + 1;  // point 3: 每次自增加1个byte
        }
       return s; }

    函数原型:

    void * memcpy(void *dest, const void *src, size_t len);
    void *myMemcpy(void *dest, const void *src, size_t n)   // ponit1: src声明为const类型 & 指定n个需要cp的字节
    {
        assert(NULL != dest && NULL != src);
        int i = 0;
        void *tmp = dest;
        while(i < n){
            *((char *)tmp + i) = *((char *)src + i);
            ++ i;
        }
        return dest;
    }

    函数原型:

    int atoi(const char *nptr);

      实现过程主要注意:int范围是否合理(用long long 和 int的最大值与最小值(最小值的表示-0)比较),符号的处理,非法字符,正负号。

    const int INF_MAX = 0x7fffffff;
    const int INF_MIN = 0x80000000;
    enum  {Invalid = 0, Valid};
    int errno;
    void atoiCore(const char *str, bool minus, long long &num)
    {
        while( '' != *str ){
            cout<<"str : "<<*str<<endl;
            if(*str >= '0' && *str <= '9'){
                num = num * 10 + (*str) - '0';
                str ++;
                if( (minus &&  -num < INF_MIN) || (!minus && num > INF_MAX)){ //超过int范围
                    errno = Invalid;
                    num = 0;
                    return ;
                }
            }else{ // 非数字字符
                errno = Invalid;
                num = 0;
                return ;
            }
        }
        if ( minus )
            num = -num;
        errno = Valid;
    }
    
    //负数最小值(-2^31)的补码使用的是 -0的补码 负数最小值的补码使用的是 -0的补码 负数最小值的补码使用的是 -0的补码
    int myAtoi(const char* str)
    {
        assert( NULL != str);
        long long num = 0;  // point 1: 过程可能会溢出 使用long long
        errno = Invalid;
        if (*str != '')// point 2
        {
            bool minus = false;
            if (*str == '+'){
                ++ str;
            }else if(*str == '-'){
                ++ str;
                minus = true;
            }
            if('' != *str){
                atoiCore(str, minus, num);
            }
        }
        return (int) num; //保证范围后 返回 int
    }
  • 相关阅读:
    Open source cryptocurrency exchange
    Salted Password Hashing
    95. Unique Binary Search Trees II
    714. Best Time to Buy and Sell Stock with Transaction Fee
    680. Valid Palindrome II
    Java compiler level does not match the version of the installed Java project facet.
    eclipse自动编译
    Exception in thread "main" java.lang.StackOverflowError(栈溢出)
    博客背景美化——动态雪花飘落
    java九九乘法表
  • 原文地址:https://www.cnblogs.com/luntai/p/6472590.html
Copyright © 2011-2022 走看看