使用指针参数将固定大小的数组传递给函数 [英] Pass fixed sized array to a function with pointer argument
本文介绍了使用指针参数将固定大小的数组传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有一种方法可以使以下代码正常工作,还是必须为固定大小的函数创建一个新副本?如果可以的话,如何为固定尺寸提供通用功能.
I'm wondering is there a way to get the following code to work, or do I have to create a new copy of the function for fixed sizes? If so how can I have a generic function for fixed sizes.
void prettyPrintMatrix_float(float **matrix, int rows, int cols){
int i, j;
for (i = 0; i<rows; i++){
for (j = 0; j<cols; j++){
printf("%10.3f", matrix[i][j]);
}
printf("\n");
}
return;
}
float ppArray[4][10] = {0.0f};
prettyPrintMatrix_float(ppArray, 4, 10);
给出错误Access violation reading location 0xFFFFF...
.
推荐答案
如果编译器支持可变长度数组,则可以定义函数,如
If the compiler supports Variable Length Arrays then you can define the function like
void prettyPrintMatrix_float( int rows, int cols, float matrix[rows][cols] ){
int i, j;
for (i = 0; i<rows; i++){
for (j = 0; j<cols; j++){
printf("%10.3f", matrix[i][j]);
}
printf("\n");
}
}
否则,您可以定义类似的功能
Otherwise you can define the function like
void prettyPrintMatrix_float(const float *matrix, int rows, int cols)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
printf("%10.3f", matrix[i * cols + j]);
}
putchar('\n');
}
}
并称呼它
prettyPrintMatrix_float( ( const float * )ppArray, 4, 10);
这篇关于使用指针参数将固定大小的数组传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文