我在我的智慧結尾,我的朋友。將地址返回到二維數組中的一行值的函數?
該函數的目的是獲取一個指向二維數組,行號和列大小的指針,並返回指向二維數組中指定行值的地址。我不知道如何完成此任何建議?
在此先感謝。
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";
}
這取決於你是如何代表你的二維數組。它是一個數組的數組還是一個包含每一行的單個數組?你的函數論證似乎暗示了後者,但你的實現似乎暗示了前者。 –
歡迎來到Stack Overflow。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –
_「但我不確定我是否已經正確實施。」_這就是測試用例的用途。 –