gpt4 book ai didi

c - 这种复制字符串的方法是否比单独复制每个字符更快?

转载 作者:太空宇宙 更新时间:2023-11-04 07:04:32 25 4
gpt4 key购买 nike

这种复制字符串的方法是否比单独复制每个字符更快?这段代码的想法是它可以(但我不确定是否如此)一次复制 8 个字节而不是单个字节更快。这是非常不安全的,但它似乎以某种方式工作。或者这只是个坏主意?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void* copy_string(char s[])
{
int len=strlen(s);
int i=0;

double *p=(double*)s;
double *copy=(double*)malloc(len+1);

while(i-len>8)
{
*copy=*(p++);
copy++;
i+=8;
}
char *p2=(char*)p;
char *c=(char*)copy;
while(i<len)
{
*c=*(p2++);
c++;
i++;
}
*c='\0';
return copy;
}

int main()
{
char s[]="GOODBYE SAFE WORLD!";
char *c=copy_string(s);
printf("%s",c);
return 0;
}

最佳答案

像这样的技巧可能在某些情况下在某些架构上更快。如果适用,请相信您的 C 库提供商了解这些技巧。

在您的情况下,您的代码完全是错误的。假设第一个 while 循环的条件是固定的,则违反了指针转换的规则:

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined.

在许多架构上,这只会导致“总线错误”。

要了解这些技巧是如何工作的,请查看您最喜欢的 C 库的源代码并查找它们对 memcpymemmove 的实现。

关于c - 这种复制字符串的方法是否比单独复制每个字符更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34335909/

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