【发布时间】:2018-04-05 16:38:32
【问题描述】:
我正在尝试从我的 3D 动态数组的每个切片中删除前 20 列。我猜想尝试为 2D 动态数组编写一个函数将解决我将遍历 3D 数组的每个级别的问题。我在 stackoverflow 中有一个示例,我正在尝试使其工作。
但问题是函数不能删除整列。相反,它只删除一个元素。谁能告诉我如何从二维动态数组中删除整列?
void removeColumn(int** matrix, int col){
MATRIX_WIDTH--;
for(int i=0;i<MATRIX_HEIGHT; i++) {
while(col<MATRIX_WIDTH)
{
//move data to the left
matrix[i][col]=matrix[i][col+1];
col++;
} matrix[i] = realloc(matrix[i], sizeof(double)*MATRIX_WIDHT); }
我的预期输出就像 示例输入:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
样本输出:
1 3 4
5 7 8
9 11 12
13 15 16
更新:这是使用@frslm 建议后完全删除列的代码 但矩阵没有调整大小。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int** fill(size_t rows, size_t cols, int input[][cols])
{
int i,j,count=1;
int** result;
result = malloc((rows)*sizeof(int*));
for(i=0;i<rows;i++)
{
result[i]=malloc(cols*sizeof(int));
for(j=0;j<cols;j++)
{
result[i][j]=count++;
}
}
return result;
}
void printArray2D(size_t rows, size_t cols,int** input)
{
int i,j;
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
printf(" %4d",input[i][j]);
}
printf("\n");
}
}
void removeColumn(int** matrix, int col2del , int rows, int cols){
int MATRIX_WIDTH = cols;
int MATRIX_HEIGHT = rows;
MATRIX_WIDTH--;
for(int i=0;i<MATRIX_HEIGHT; i++) {
int curr_col = col2del;
while(curr_col<MATRIX_WIDTH)
{
//move data to the left
matrix[i][curr_col]=matrix[i][curr_col+1];
curr_col++;
}
//matrix[i] = realloc(matrix[i], sizeof(int)*MATRIX_WIDTH); // <- int, not double
matrix[i] = realloc(matrix[i], sizeof (matrix[i][0])*MATRIX_WIDTH);
}
}
int main()
{
int arRow,arCol;
arRow =8;
arCol = 9;
int ar[arRow][arCol];
int **filled;
filled = fill(arRow, arCol, ar);
printArray2D(arRow,arCol,filled);
removeColumn(filled, 3,arRow,arCol);
printf("After 3rd Column Delete.......\n");
printArray2D(arRow,arCol,filled);
return(0);
}
输出:最后一列重复
1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18
19 20 21 22 23 24 25 26 27
28 29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54
55 56 57 58 59 60 61 62 63
64 65 66 67 68 69 70 71 72
After 3rd Column Delete.......
1 2 3 5 6 7 8 9 9
10 11 12 14 15 16 17 18 18
19 20 21 23 24 25 26 27 27
28 29 30 32 33 34 35 36 36
37 38 39 41 42 43 44 45 45
46 47 48 50 51 52 53 54 54
55 56 57 59 60 61 62 63 63
64 65 66 68 69 70 71 72 72
【问题讨论】:
-
int input[][cols]未在fill(size_t rows, size_t cols, int input[][cols])中使用。为什么要有那个参数? -
@chux 有什么不同吗?但是,我实际上是在尝试学习传递数组的不同方法。
-
它确实有所作为。在没有解释的情况下将未使用的参数传递给函数会减损和混淆问题。因此,需要澄清的问题。
-
MATRIX_WIDTH--;应仅在cols < MATRIX_WIDTH时出现。
标签: c