使用指针算法搜索 2D 数组

Searching a 2D array with pointer arithmetic

本文关键字:2D 数组 搜索 算法 指针      更新时间:2023-10-16

对于家庭作业,我们被告知要编写在 2D 矩阵上运行的 sum、find_max 和 find_min 等函数。我会使用这样的东西来正常找到最大值。

double find_max(double *the_array, int row_size, int col_size) {
    double maxValue = *the_array[0][0];
    for (int i = 0; i < col_size; i++) {
         for (int j = 0; j < row_size; j++) {
             if (*the_array[i][j] > maxValue) {
                  maxValue = *the_array[i][j];
             }
         }
     }
 }

但是,我们被告知要使用指针而不是数组来完成此作业。我猜这意味着我需要使用指针算法来遍历数组,但我不确定该怎么做。我使用哪种循环?我怎么知道什么时候告诉它停止?

>the_array应该是双精度指针的指针。我的意思是: double find_max(double **the_array, int row_size, int col_size)

像这样您的the_array实际上只是大小行 * col 的线性记忆。

double find_max(double *the_array, int row_size, int col_size)
{
    double *iterator = the_array;
    double *end = the_array + row_size * col_size;
    double max = DBL_MIN;
    while (iterator < end) {
        if (*iterator > max)
            max = *iterator;
        ++iterator;
    }
    return max;
}