手撕内存操作函数

内存复制memcpy

#include
#include

void* my_memcpy(void *dest, const void *src, size_t count)
{
     
    char *tmp = dest;
    const char *s = src;
 
    while(count--){
     
        *tmp++ = *s++ ;
    }
    
    return dest;
}

int main()
{
     
    char* buf1 = "abcdefghijklmnopqrstuvwxyz";
    char* buf2 = malloc(27); 

    my_memcpy(buf2,buf1,27);
    printf("buf1 = %s \r\n",buf1);   
    printf("buf2 = %s \r\n",buf2);

    free(buf2);
    return 0;
}

内存复制,改进memcpy

#include
#include

void* my_memcpy(void *dest, const void *src, size_t count)
{
     
    char *d;
    const char *s;
 
    if((dest > (src+count)) || (dest < src)){
     
        d = dest;
        s = src;
        while (count--){
     
            *d++ = *s++;
        }        
    }else{
      /* overlap */
        d = (char *)(dest + count - 1); /* offset of pointer is from 0 */
        s = (char *)(src + count -1);
        while (count --){
     
            *d-- = *s--;
        }
    }
  
    return dest;
}

int main()
{
     
    char* buf1 = "abcdefghijklmnopqrstuvwxyz";
    char* buf2 = malloc(27); 

    my_memcpy(buf2,buf1,27);
    printf("buf1 = %s \r\n",buf1);   
    printf("buf2 = %s \r\n",buf2);

    free(buf2);
    return 0;
}

内存设置memset

#include
#include

void* my_memset(void *s,int c,size_t n)
{
     
    const unsigned char uc = c;
    unsigned char *su;
    for(su = s;0 < n;++su,--n){
     
        *su = uc;
    }
		
    return s;
}

int main()
{
     
    char* buf1 = malloc(6);    
    my_memset(buf1,'1',5);
    buf1[5] = '\0';
    printf("buf1 = %s \r\n", buf1);
    free(buf1);

    char* buf2 = malloc(6);    
    my_memset(buf2,'8',5);
    buf2[5] = '\0';
    printf("buf2 = %s \r\n", buf2);
    free(buf2);

    return 0;
}

你可能感兴趣的:(指针,数据结构)