C语言内存函数

目录

memcpy使用和模拟实现

memmove使用和模拟实现

memset函数的使用

memcmp函数的使用


memcpy使用和模拟实现

函数memcpy从source的位置开始向后复制num个字节的数据到destination指向的内存位置。
这个函数在遇到 '\0' 的时候并不会停下来。
如果source和destination有任何的重叠,复制的结果都是未定义的。
#include <stdio.h>
#include <string.h>
int main() {
    int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int arr2[10] = { 0 };
    memcpy(arr2, arr1, 20);
    int i = 0;
    for (i = 0; i < 10; i++) {
        printf("%d ", arr2[i]);
    }
    return 0;
}
对于重叠的内存,交给memmove来处理。
memcpy函数的模拟实现:
void* memcpy ( void* dst, const void* src, size_t count) {
    void* ret = dst;
    assert(dst&&src);
    while (count--) {
        *(char*)dst = *(char*)src;
        dst = (char*)dst + 1;
        src = (char*)src + 1;
    }
    return (ret);
}

memmove使用和模拟实现

和memcpy的差别就是memmove函数处理的源内存块和⽬标内存块是可以重叠的。
如果源空间和⽬标空间出现重叠,就得使⽤memmove函数处理。
#include <stdio.h>
#include <string.h>
int main() {
    int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    memmove(arr1 + 2, arr1, 20);
    int i = 0;
    for (i = 0; i < 10; i++) {
        printf("%d ", arr1[i]);
    }
    return 0;
}
memmove的模拟实现:
void* memmove ( void* dst, const void* src, size_t count) {
    void* ret = dst;
    if (dst <= src || (char*)dst >= ((char*)src + count)) {
        while (count--) {
            *(char*)dst = *(char*)src;
            dst = (char*)dst + 1;
            src = (char*)src + 1;
        }
    } else {
        dst = (char*)dst + count - 1;
        src = (char*)src + count - 1;
        while (count--) {
            *(char*)dst = *(char*)src;
            dst = (char*)dst - 1;
            src = (char*)src - 1;
        }
    }
    return (ret);
}

memset函数的使用

memset是⽤来设置内存的,将内存中的值以字节为单位设置成想要的内容
#include <stdio.h>
#include <string.h>
int main () {
    char str[] = "hello world";
    memset (str, 'x', 6);
    printf(str);
    return 0;
}

输出的结果是:

xxxxxxworld

memcmp函数的使用

比较从ptr1和ptr2指针指向的位置开始,向后的num个字节
返回值(见上图Retrun Value)
#include <stdio.h>
#include <string.h>
int main() {
    char buffer1[] = "DWgaOtP12df0";
    char buffer2[] = "DWGAOTP12DF0";
    int n;
    n = memcmp(buffer1, buffer2, sizeof(buffer1));
    if (n > 0)
        printf("'%s' is greater than '%s'.\n", buffer1, buffer2);
    else if (n < 0)
        printf("'%s' is less than '%s'.\n", buffer1, buffer2);
    else
        printf("'%s' is the same as '%s'.\n", buffer1, buffer2);
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值