2

我在 C 中有一个二维数组,如下所示:

int pop[18000][3] = {
  0, 1, 24,
  0, 2, 46,
  /* many other rows */
  6, 17999, 10,
  6, 18000, 10,
};

我想要做的是编写一个函数来检查每一行的最后一个值,如果它有某个值,则返回整行。我知道我可以用凌乱的方式做到这一点

for (i = 0; i <= 2; i++)
  if (pop[i][1] == 10)
    printf("%d, %d, %d\n", pop[i][0], pop[i][1], pop[i][2]);

但我实际上正在寻找一种更通用的解决方案,允许我打印选定的整行(例如,在某些模拟中,我最终可能会创建具有数十列(如果不是数百列)的二维数组;我不想为此使用凌乱的方法)。

4

3 回答 3

2
for(i=0;i<18000;i++)
{

 if(pop[i][2] == 10) // u sed last column
 for(j=0;j<3;j++)
       printf("%d",pop[i][j]);
 }

有帮助吗?

于 2013-04-11T14:04:42.830 回答
0

I would allocate a one-dimensional array of length rows*columns and use the following function:

void print(int *pop, int index, int value, int rows, int columns) {

    int i,j;

    for(i=0; i<rows; i++) {
        if(pop[i+(j-1)*index] ==  value) {
            for(j=0; j<columns; j++) {
                printf("%d, ", pop[i+j*columns]);
            }
            printf("\n");
        }
    }
}

When you call the function you simply pass the array as argument with the number of rows and columns it has and the column number index on which you want to check for the value value. In this way you can use the function for any two-dimensional array for an arbitrary column number and value

// ...

int rows = 18000;
int columns = 3;
int index = 3;
int value = 10;
int *pop = malloc(sizeof(int)*rows*columns);

// Fill your pop array here

print(pop, index, value, rows, columns);

// ...
于 2013-04-11T14:13:19.420 回答
0

使用辅助功能:

void printArray(int *array, int length) {
    for (int i = 0; i < length; ++i) {
       printf("%d", array[i]);
    }

    printf("\n");
}

用法 :

for (i = 0; i < ROWS_COUNT; i++)
  if (pop[i][COLUMNS_COUNT - 1] == 10)
     printArray(pop[i], COLUMNS_COUNT); 
于 2013-04-11T14:05:18.270 回答