C 给定一个2D数组-我想使用原始数组中的值创建一个新数组
我已经写了一些代码,从2D数组中取四个单元格的平均值。条件是列和行必须是偶数,如果不是,则忽略最后一列/行 我忘了提到这是头文件的一部分-2D数组被定义为包含main()的另一个文件中的数组[x][y]。pastebin.com/LUXW5X6b 鉴于此,我认为最好的方法是使用指针和malloc访问堆并进行更改。->我将如何着手实现这一点C 给定一个2D数组-我想使用原始数组中的值创建一个新数组,c,pointers,2d,C,Pointers,2d,我已经写了一些代码,从2D数组中取四个单元格的平均值。条件是列和行必须是偶数,如果不是,则忽略最后一列/行 我忘了提到这是头文件的一部分-2D数组被定义为包含main()的另一个文件中的数组[x][y]。pastebin.com/LUXW5X6b 鉴于此,我认为最好的方法是使用指针和malloc访问堆并进行更改。->我将如何着手实现这一点 uint8_t *half(const uint8_t array[], unsigned int cols,
uint8_t *half(const uint8_t array[],
unsigned int cols,
unsigned int rows) {
// your code here
int i, j;
uint8_t new_rows = rows / 2;
uint8_t new_cols = cols / 2;
uint8_t new_array[new_rows][new_cols];
if (new_rows % 2 != 0) {
new_rows = new_rows - 1;
}
if (new_cols % 2 != 0) {
new_cols = new_cols - 1;
}
for (i = 0; i < new_rows; i++) {
for (j = 0; j < new_cols; j++) {
new_array[i][j] = average(array[2*i][2*j],
array[2*i+1][2*j],
array[2*i+1][2*j+1],
array[2*i][2*j+1]);
}
}
return NULL;
}
uint8_t*half(const uint8_t数组[],
无符号整数列,
无符号整数行){
//你的代码在这里
int i,j;
uint8新的行=行/2;
uint8新列=列/2;
uint8_t new_数组[新行][新列];
如果(新行%2!=0){
新行=新行-1;
}
如果(新列%2!=0){
new_cols=new_cols-1;
}
对于(i=0;i<新行;i++){
对于(j=0;j
必须将参数数组声明为2D数组。在C99中,可以使用以下语法指定尺寸:
uint8_t *half(unsigned int cols, unsigned int rows,
const uint8_t array[][cols]) {
}
还有一个问题:您无法在自动存储中返回指向本地数组的指针,因为该对象在函数返回后立即无效。一个简单的解决方案是在调用者函数中分配目标数组,并传递给函数half
:
int half(unsigned int cols, unsigned int rows,
const uint8_t array[rows][cols],
uint8_t output[rows / 2][cols / 2])
{
unsigned int new_rows = rows / 2;
unsigned int new_cols = cols / 2;
for (unsigned int i = 0; i < new_rows; i++) {
for (unsigned int j = 0; j < new_cols; j++) {
output[i][j] = average(array[2 * i ][2 * j ],
array[2 * i + 1][2 * j ],
array[2 * i + 1][2 * j + 1],
array[2 * i ][2 * j + 1]);
}
}
return 1;
}
还要注意的是,由于整数除法已经向0舍入,因此对
新行
和新列
的额外测试似乎是不必要的。如果原始数组的维数为奇数,则会正确计算缩减后的数组,忽略最后一行和/或列。array[]是1d..Yee,谢谢你让我意识到我忘记了在main()中预定义数组的细节。这是我的主要任务-
int half(unsigned int cols, unsigned int rows,
const uint8_t array[][cols],
uint8_t output[][cols / 2]) ...