我有一堆:
static const int blockFrames1[4][9]= {{0,1,1, 0,1,1, 0,1,1},{0,0,0, 1,1,1, 1,1,1},{0,1,1, 0,1,1, 0,1,1},{0,0,0, 1,1,1, 1,1,1}};
我想将其中一个内部数组分配给一个临时变量,以便在函数中使用,如下所示:
int tempArr[9];
if(type == 1){
tempArr[9] = blockFrames1[0];
}else if(type ==2){
tempArr[9] = blockFrames2[0];
}
(for loop thru and do some stuff with tempArr)
但我能让它工作并给我正确数字的唯一方法是实际循环并分配每个数字:
if(type == 1){
for (int vv=0; vv<9; vv++) {
tempArr[vv] = blockFrames1[0][vv];
}
}
似乎我在声明 tempArr
时需要 [9]
来定义长度,但是当我尝试将现有数组之一分配给它时它搞砸了这个新的有或没有 [9]
。
最佳答案
数组不可赋值。如果你想填充它们,那么只需memcpy()
。另外,是的,您需要声明中的维度(好吧,如果您初始化数组则不需要),但是如果您在声明之外使用方括号语法,那么它已经在索引/下标数组,以便访问它的元素。
总而言之:
// declaration
int array[9];
// assignment to one element
array[0] = 42;
// "assignment" to another array - rather a bytewise copy
int other_array[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
memcpy(array, other_array, sizeof(array));
关于c - 只有在循环中分配每个单独的元素时,数组的分配才会成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15911599/