gpt4 book ai didi

c - 是否可以有效地替代 memmove() 函数?

转载 作者:行者123 更新时间:2023-11-30 18:14:30 33 4
gpt4 key购买 nike

我正在尝试移动可能重叠的内存,对 *src 和 *dst 使用负增量或正增量,并且不使用大型临时缓冲区。

我正在尝试为 memmove() 函数找到一个有效的替代方案,大致如下:

smart_memmove(char *dst, const char *src, size_t num, int dst_inc, int src_inc);

dst 和 src 可以重叠,并且 dst_inc 和 src_inc 可以是任何正整数或负整数(负增量表示在内存中向后移动,起始指针位于顶部)。我想避免使用较大的临时缓冲区,即使这意味着执行速度会降低。

举个例子,从内存位置 0 开始,每隔一个字节递增一次,将 10 个字节复制到内存位置 17,并向后计数 1:

smart_memmove(17, 0, 10, -1, 2);

另一个例子是,通过使用以下参数调用 smart_memmove 来反转内存位置 6、9、12、15、18、21、24、27、30、33 中的 10 个字节序列:

smart_memmove(6, 33, 10, 3, -3); /* or... smart_memmove(33, 6, 10, -3, 3); */

最佳答案

您也可以更喜欢 memcpy() 函数。

void * memcpy ( void * destination, const void * source, size_t num );

目的地指向要复制内容的目标数组的指针,类型转换为 void* 类型的指针。

来源指向要复制的数据源的指针,类型转换为 const void* 类型的指针。

数字要复制的字节数。

size_t 是无符号整数类型。

将 num 个字节的值从源指向的位置直接复制到目标指向的内存块。

源指针和目标指针所指向的对象的基础类型与该函数无关;结果是数据的二进制副本。

该函数不会检查源中是否有任何终止空字符 - 它始终精确复制 num 个字节。

为避免溢出,目标参数和源参数指向的数组大小至少应为 num 个字节,并且不应重叠(对于重叠的内存块,memmove 是更安全的方法)。

示例程序

/* memcpy example */
#include <stdio.h>
#include <string.h>

struct {
char name[40];
int age;
} person, person_copy;

int main ()
{
char myname[] = "user613994";

/* using memcpy to copy string: */
memcpy ( person.name, myname, strlen(myname)+1 );
person.age = 46;

/* using memcpy to copy structure: */
memcpy ( &person_copy, &person, sizeof(person) );

printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );

return 0;
}

关于c - 是否可以有效地替代 memmove() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7721199/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com