Я имею дело с произвольной размерной матрицей / массивом, поэтому мне нужно получить доступ к многомерному массиву с помощью указателей.
Я попытался написать функцию, которая извлекает определенный столбец многомерного в C:
Я следовал нескольким принятым ответам: Как использовать выражения указателя для доступа к элементамдвумерного массива в C?
Вот мой код C:
#include <stdio.h>
//prototype
void get_column_vector_from_matrix (float * info, int rows,
int column_dimension, float * single_dimension);
//main
int main()
{
//test data
float points[][3] = {{3, -2, 1},
{17, 15, 1},
{13, 15, 1},
{6, 12, 12},
{9, 1, 2},
{-1, 7, 2},
{10, 17, 2},
{10, 20, 2}};
int rows = sizeof(points)/sizeof(points[0]);
float single_dimension [rows];
//extract column vector 0, therefore 3,17,13,7,9,-1,10,10 should be returned
get_column_vector_from_matrix(&points,rows,0,single_dimension);
printf("Column 0\n");
for (int i=0; i<rows; i++)
{
printf("data[%i]=%f\n",i,single_dimension[i]);
}
//extract column vector 1, therefore -2,15,15,12,1,7,17,20 should be returned
get_column_vector_from_matrix(&points,rows,1,single_dimension);
printf("Column 1\n");
for (int i=0; i<rows; i++)
{
printf("data[%i]=%f\n",i,single_dimension[i]);
}
//extract column vector 2, therefore 1,1,1,1,2,2,2,2 should be returned
get_column_vector_from_matrix(&points,rows,2,single_dimension);
printf("Column 2\n");
for (int i=0; i<rows; i++)
{
printf("data[%i]=%f\n",i,single_dimension[i]);
}
}
/*=============================================================================
Function: get_column_vector_from_matrix
Description: this function points to an arbitrary multidimensional array of
* dimensions m(rows) by n(columns) and extracts a single dimension
* with all rows. This attempts to extract column vector given a
* m(rows) by n(columns) matrix.The pointer to extracted column is
* set to float * single_dimension parameter.
*
=============================================================================*/
void get_column_vector_from_matrix (float * info, int rows,
int column_dimension, float * single_dimension)
{
int row_i=0;
float value = 0;
if (info!=NULL && single_dimension!=NULL)
{
//return data only at column_dimension
for ( row_i; row_i< rows; row_i++ ) {
//(*(info+row_i)+column_dimension) below is based on https://stackoverflow.com/questions/13554244/how-to-use-pointer-expressions-to-access-elements-of-a-two-dimensional-array-in/13554368#13554368
value = (float)(*(info+row_i)+column_dimension);
*(single_dimension+row_i) = value;
}//end
}
}
Вызов get_column_vector_from_matrix(&points,rows,1,single_dimension);
При возврате извлечение должно вернуть 3,17,13,7,9, -1,10,10, однако его возвращение
Колонка 0
data [0] = 3.000000
data [1] = -2,000000
данные [2] = 1,000000
данные [3] = 17,000000
данные [4] = 15,000000
данные [5] = 1,000000
данные [6] = 13,000000
данные[7] = 15,000000