gpt4 book ai didi

c - Memcpy 一个 str[ ] 到 str*

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

我正在尝试创建一个异或函数(我想异或 2 个字符串并返回结果)。

为此,我需要将数组 (str[ ]) 的内容复制到字符串 (str*)。

char* xor(char* str1, char* str2)
{
char temp[strlen(str1)];
char* result = NULL;
int i;

for(i=0; i<=strlen(str1); i++)
{
temp[i] = str1[i] ^ str2[i];
}
memcpy(result,temp,sizeof(temp)+1);
return result;
}

我的 memcpy 出现段错误。

我错过了什么吗?你能帮帮我吗?

最佳答案

您没有为result 分配内存,而是将NULL 传递给了memcpy();这是未定义的行为。

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

char *xor(char const *a, char const *b) {
size_t const size = strlen(a);
if (size != strlen(b)) {
return NULL;
}

char *result = malloc(size + 1);
if (!result) {
return NULL;
}

for (size_t i = 0; i < size; i++) {
result[i] = a[i] ^ b[i];
}
result[size] = '\0';

return result;
}

关于c - Memcpy 一个 str[ ] 到 str*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47697791/

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