【问题标题】:My memcpy implementation fails我的 memcpy 实现失败
【发布时间】:2013-10-12 09:34:55
【问题描述】:

在了解代码以及根据接收到的数据需要字节传输或字传输之后,我正在尝试 memcpy.c 实现。

#include<stdio.h>

void* my_memcpy(void*,const void*,int); // return type void* - can return any type

struct s_{
        int a;
        int b;
};

int main(){
        struct s_ ss,dd;
        ss.a = 12;
        ss.b = 13;
        printf("\n sizeof(struct) : %d \n",sizeof(ss));
        my_memcpy(&dd,&ss,sizeof(ss));
        printf("\n a:%d b:%d \n",dd.a,dd.b);
        return 0;
}

void* my_memcpy(void* s,const void* d,int count){
        if(((s | d | count) & (sizeof(unsigned int)-1)0)){
                char* ps = (char* )s;
                char* pd = (char* )d;
                char* pe = (char* )s + count;
                while(ps != pe){
                        *(pd++) = *(ps++);
                }
        }
        else{
                unsigned int* ps = (unsigned int* )s;
                unsigned int* pd = (unsigned int* )d;
                unsigned int* pe = (unsigned int* )s + count;
                while(ps != pe){
                        *(pd++) = *(ps++);
                }
        }
}

错误:二进制操作数无效 | (void* 和 const void*)。

我不能使用 const void* 或 void*。

在我之前在 Understanding the implementation of memcpy() 中提出的问题中,它的类型转换为 (ADDRESS)。

有什么办法可以解决这个错误?

【问题讨论】:

  • 另一个问题非常清楚地解释了为什么需要类型转换。你为什么把它拿出来?布尔运算符只能接受整数参数,不能接受指针——您需要将指针转换为无符号整数。
  • @Barmar 应该说“位运算符”吧?
  • if 语句格式错误。错字? C 还保证无符号整数至少有两个字节大(16 位)。并且 count 在第二个 while 循环中使用不正确。需要计算结构中的整数,而不是 sizeof 结构的字节数。
  • 另外在另一个问题中,第三个参数的类型正确,即sizeof。不要使用int 来表示尺寸,它只会给你带来麻烦。
  • 您的问题与您对memcpy 的实现无关。您很清楚,演员表有助于在另一个问题中进行按位运算,没有它就不能在指针上工作。那么你为什么不直接问这个问题,而是把所有这些都发给我们呢?那么您可能已经找到了 Vadiklk 自己链接到的其他问题和答案。

标签: c


【解决方案1】:

根据标准,您不能对指针使用按位运算: Why can't you do bitwise operations on pointer in C, and is there a way around this?

简单的解决方案(链接中也指出)是使用强制转换。

【讨论】:

    【解决方案2】:
    (s | d | count)
    

    你应该使用逻辑或 ||而不是按位或|,因为我假设您在这里检查这些参数,s 和 d 不应为 NULL,count 不应为零。

    和&一样,应该是&&。

    【讨论】:

    • 不,他们正在检查 sd 是否在 sizeof(unsigned int) 字节边界对齐。在这里使用逻辑运算符会产生不正确的结果。
    猜你喜欢
    • 1970-01-01
    • 2013-10-11
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2021-12-28
    • 2015-02-01
    相关资源
    最近更新 更多