【C++】函式將地址返回到二維陣列中的一行值?

2021-01-29 C++

我的朋友們,我已經快要死了。

此函式的目的是獲取一個指向2D陣列,行號和列大小的指標,並返回指向2D陣列中值的指定行的地址。我不確定如何做到這一點,有什麼建議嗎?

提前致謝。

double* get_row(double *the_array, int row_num, int col_size) {
cout << "Get Row : "<< the_array[row_num]<< "\n";
return the_array+row_num;}


cout的原因是要確認它是我返回的指標的正確值集,但我不確定我是否正確實現了該值。

編輯:

這是完整的程式碼

#include "TwoDArray.h"

using namespace std;

/*
 * 
 */

void set_row(double *the_array, int row_num, int col_size, double *row_vals) {
    for (int i = 0; i < col_size; i++)
        the_array[i] = *row_vals + i;
    cout << "Set Row:"<< *the_array << "\n";
}

double get_element(double *the_array, int row_num, int col_size, int col_num) {
    double thisElement = (*(the_array + (row_num * col_size)) + col_num);
    return thisElement;
}

double* get_row(double *the_array, int row_num, int col_size) {
    cout << "Get Row : "<< the_array[row_num]<< "\n";
    return the_array+row_num;
}

double sum(double *the_array, int row_size, int col_size) {

    double sum = 0.0;
    for (int j = 0; j < row_size; j++) {
        for (int i = 0; i < col_size * row_size; i++) {
            sum += the_array[i] + j;

        }
        return sum;
    }
}

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

double find_min(double *the_array, int row_size, int col_size) {
    double min_so_far = the_array[0];
    for (int j = 0; j < row_size; j++)
        for (int i = 0; i < col_size * row_size; i++)
            if (the_array[i] + j < min_so_far)
                min_so_far = the_array[i] + j;
    return min_so_far;


}

int main(int argc, char** argv) {

    const int row_size = 2; //i
    const int col_size = 3; //j
    double B[2][3] = {
        {68, 2, 44},
        {7, 8, 3}
    };
    double (*p)[3] = B;
    double C[2][3] = {
        {1, 1, 1},
        {1, 2, 3}};

    double (*f)[3] = C;

    cout << "\n" << "Sum of all Elements = " << sum(*p, 2, 3) << "\n"; ///Expected: 132
    cout << "\n" << "Get Element = " << get_element(*p, 1, 0, 0) << "\n"; //Expected: 68
    cout << "\n" << "Largest Element = " << find_max(*p, 2, 3) << "\n"; //Expected: 68
    cout << "\n" << "Smallest Element = " << find_min(*p, 2, 3) << "\n"; //Expected: 2
    cout << "\n" << "Get Row = " << get_row(*p, 0, col_size) << "\n"; //Expected: 2
    set_row(*p, 2, 3, *f);
    cout << "\n" << B[2][3];
    cout << "\n";



}

解決辦法

x + y * col_sizex是二維陣列座標時,y給出陣列的一維索引。因此,要訪問行的第一個元素,您可以設定x = 0y = row_num。不只是返回您元素的地址。

return &the_array[row_num * col_size];

出處

Have any Question?

Let us answer it!