【发布时间】:2013-12-15 22:44:39
【问题描述】:
在 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
}
【问题讨论】:
-
很难说你到底想做什么。你能澄清一下你的问题吗?
-
它是一个不能被重写的常量对象数组。它将替换一个指向此类目的的指针。
-
如果您期望 a[1] 具有 out[1] 的值,它不会。 *a 等价于 a[0] 而 *out 等价于 o out[0]。最终结果是 a[0] 获得了 out[0] 的值,并且 a[1] 被保留为它在步骤 *a = *out; 之前的任何值
-
数组不可赋值。就是这样。
标签: c arrays function pointers swap