2013-10-05 28 views
0

我想了解代碼和需要字節傳輸或字傳輸取決於接收到的數據後的memcpy.c實現。我的memcpy實現失敗

#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 *。

在我之前問過的Understanding the implementation of memcpy()的問題中,它被稱爲(ADDRESS)。

可以做些什麼來解決這個錯誤?

+1

另一個問題非常清楚地解釋了爲什麼需要類型轉換。你爲什麼把它拿出來?布爾運算符只能使用整數參數,而不能使用指針 - 您需要將指針轉換爲無符號整數。 – Barmar

+0

@Barmar應該說「按位運算符」,對不對? – us2012

+0

if語句格式錯誤。錯字? C還保證無符號整數至少有兩個字節(16位)。並且在第二個while循環中count被錯誤地使用。需要在結構中進行整數計數,而不是以字節爲單位的sizeof結構。 – willus

回答

-2
(s | d | count) 

您應該使用邏輯或|而不是按位或|,因爲我想你在這裏檢查這些參數,s和d不應該爲NULL,count不應該爲零。

與&相同,應該是& &。

+0

不,他們正在檢查's'和'd'是否在'sizeof(unsigned int)'字節邊界對齊。使用邏輯運算符會在這裏產生不正確的結果。 – ApproachingDarknessFish