2013-12-15 54 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指向的内存(除了使用自动分配数组的第一个调用除外)。

最后,这和你的原始代码并不真正交换数组。代码只是分配一个新的数组来替代旧数组。但我认为这回答了你的问题的本质。