c - 只有在循环中分配每个单独的元素时,数组的分配才会成功

标签 c arrays

我有一堆:

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/

相关文章:

java - 在 JOptionPane 中显示(字符串)数组的内容

java - 二维和一维数组

c - 程序的数据部分是否太大?

c - 如果使用函数,编译器会发出警告

c - 如何检查 c 中 fscanf 的行为?

java - 将字符串数组从 red5 (Java) 发送到 Flash (ActionScript 3)?

arrays - CouchDB:在文档中插入一个新数组

java - 在 Java 中使用 JPanels 的数独板

c - 用于查询和设置 bios 属性的 API

c++ - 在Linux环境中运行内联汇编(使用GCC/G++)