【发布时间】:2019-10-17 01:32:21
【问题描述】:
我正在处理任意维度的矩阵/数组,因此我需要使用指针访问多维数组。
我试图编写一个函数,在 C 中提取多维的特定列:
我遵循了几个公认的答案:How to use pointer expressions to access elements of a two-dimensional array in 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 列
数据[0]=3.000000
数据[1]=-2.000000
数据[2]=1.000000
数据[3]=17.000000
数据[4]=15.000000
数据[5]=1.000000
数据[6]=13.000000
数据[7]=15.000000
【问题讨论】: