2013-12-15 82 views
0

在C中交換數組的最佳做法是什麼?交換數組引用C

我得到了以下的用例:

void func1() { 
    uint32_t a[2] = {0x00000001,0x40000000}; 
    uint32_t t = 2; 
    do_some_magic(&t, a); 
    work_with_modefied(t,a); 
} 

void do_some_magic(uint_32_t *t,*a){ 
    //while being a magician 
    uint32_t *out; 
    out = (uint32_t *) malloc((*t+1)*4); 
    //modify a[i] and store in out[i]; 
    //some other work 
    //the tricky part 
    *t++;  // works excellent 
    // a = out  wouldn't work 
    // *a = *out wouldn't work 
} 
+5

很難說出你實際想要做什麼。你能澄清一下你的問題嗎? –

+1

沒有意義。 –

+0

這是一個不能重寫數組的常量對象。它會用一個指針來代替這個目的。 – BLUEPIXY

回答

1

你所要做的是分配a指向新分配的內存,從我收集。這不會工作,因爲a是一個數組,而不是指針。爲了實現你想要的,你需要存儲和修改指向數組的指針。您可以通過兩種方式實現交換。對於這兩種,FUNC1將是:

void func1() { 
    uint32_t t = 2; 
    uint32_t a[2] = {0x00000001,0x40000000}; 
    uint32_t * b = a; 
    b = do_some_magic(&t); 
    work_with_modified(t,b); 
} 

uint32_t * do_some_magic(uint32_t *t){ 
    *t++; 
    return malloc((*t) * sizeof(uint32_t)); 
} 

或者:

void func1() { 
    uint32_t t = 2; 
    uint32_t a[2] = {0x00000001,0x40000000}; 
    uint32_t * b = a; 
    do_some_magic(&t, &b); 
    work_with_modified(t,b); 
} 

void do_some_magic(uint32_t *t, uint32_t **b){ 
    *t++; 
    *b = malloc((*t) * sizeof(uint32_t)); 
} 

二是更接近你的原代碼。當然,在您的原始示例中錯誤檢查已被忽略。您還需要注意do_some_magic已經在堆上分配內存的事實。該內存需要稍後釋放。如果多次調用do_some_magic,則需要在每次後續調用之前釋放由b指向的內存(除了使用自動分配數組的第一個調用除外)。

最後,這和你的原始代碼並不真正交換數組。代碼只是分配一個新的數組來替代舊數組。但我認爲這回答了你的問題的本質。