2014-09-22 66 views
-4

我有兩個非常大的數組,我只想memcpy只有不同的數據。問題是如果第二個數組中有零,它也會複製零並覆蓋原始數據。問題是,零也是一個有效的數據項。我可以使用什麼算法來只存儲不同的memcpy數據?memcpy只有不同的數據

我已經試過什麼:

void *my_memcpy(void *dest, const void *src, size_t n) 
{ 
    char *dp = (char*) dest; 
    const char *sp = (char*) src; 
    while (n--) 
    { 
     if (*sp != 0) 
      *dp = *sp; 
     dp++; 
     sp++; 
    } 
    return dest; 
} 

int main() 
{ 
    int test[4] = {1, 2, 3, 4}; 
    int test2[4] = {0, 0, 0, 5}; 
    my_memcpy(test, test2, 4); 
    for (int i = 0; i < 4; ++i) 
     cout << test[i]; 
} 
+5

您需要使用某種輔助數組跟蹤修改過的數據,然後使用它來確定需要複製哪些範圍。 – 2014-09-22 16:50:30

+0

@Paul你可以發表一個例子嗎? – user4067441 2014-09-22 16:58:06

+0

通過你的描述我打算從「第二」數組中複製,而你不想從它複製零(你不想覆蓋「原始數據」)。你不能用標準庫的例程來做到這一點,你需要通過條件檢查來實現一個循環。如果您擔心此處的性能,可以使用無條件執行此副本的方法。 – Jubatian 2014-09-22 17:03:29

回答

1

有幾個問題需要需要解決的問題。

的第一個問題是,my_memcpy檢查,只有一個char一次副本,但您所陳述的要求只是複製非零int值。要理解爲什麼這是一個問題,請考慮以下兩個數組。

int test [4] = { 1, 2, 3, 4 }; 
int modified[4] = { 512, 0, 0, 0 }; 

在32位小端系統,爲這些陣列內存看起來像這樣

test  1 0 0 0 2 0 0 0 3 0 0 0 4 0 0 0 
modified 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 

呼籲my_memcpy(test, modified, sizeof(test))後的陣列內存看起來像這樣

test  1 2 0 0 2 0 0 0 3 0 0 0 4 0 0 0 

請注意,my_memcpy2複製到陣列的第二個位置,因爲2是唯一的非零char修改後的數組中的值。但是這留下了輸出數組爲

int test[4] = { 513, 2, 3, 4 }; 

這不是你想要的。


第二個問題是在main()函數中。您將值4作爲數組的大小傳遞。儘管4是數組中值爲int的數字,但它不是數組的大小。該數組由16個char值組成(在32位系統上)。因此您必須決定您傳遞給my_memcpy的尺寸是的數組的大小,還是數組中的的整數。


我建議的解決辦法是重寫my_memcpy使用int指針。

int *my_int_cpy(int *dest, const int *src, size_t count) 
{ 
    while (count--) 
    { 
     if (*src != 0) 
      *dest = *src; 
     dest++; 
     src++; 
    } 
    return dest; 
} 

int main() 
{ 
    int test[] = {1, 2, 3, 4}; 
    int test2[] = {512, 0, 0, 5}; 
    int count = sizeof(test)/sizeof(test[0]); 

    my_int_cpy(test, test2, count); 
    for (int i = 0; i < count; ++i) 
     printf("%d\n", test[i]); 
}