简体   繁体   English

如何使用 c++ 中的指针将未知大小的多维 arrays 传递到 function 中?

[英]How do I pass multi-dimensional arrays of unknown size into a function using pointers in c++?

Like the question says, I am trying to pass multi-dimensional arrays into a function to print it to a file for an engineering project.就像问题说的那样,我正在尝试将多维 arrays 传递给 function 以将其打印到工程项目的文件中。 The format for which the data is inputted CANNOT be changed, so please don't suggest I just input it as a different datatype.输入数据的格式不能更改,所以请不要建议我将其输入为不同的数据类型。

This particular function anticipates a two-dimensional array (although I have others with three dimensions after this one), where nothing is known about the size of the array until run-time.这个特殊的 function 预期一个二维数组(尽管我在这个数组之后还有其他三个维度),在运行时之前对数组的大小一无所知。 I know I must use pointers to point to each row of the array separately, but I have NO idea what the syntax is for passing it to the function.我知道我必须使用指针分别指向数组的每一行,但我不知道将它传递给 function 的语法是什么。 In the following code, the array in question is 'block'.在下面的代码中,有问题的数组是“块”。 The main function is just a little testing example I made to try to make it work:主要的 function 只是我为使其工作而制作的一个小测试示例:

#include<fstream>
using namespace std;

void of_write_blocks(string filename, string block_type[], int **block,
            int grid[][3], string grade_type[], int grade[][3], int n_blocks, int m[])
{
    ofstream file_out(filename.c_str(),ios::app);
    file_out<<"\nblocks\n(\n";

    for(int i=0;i<n_blocks;++i) {
            file_out<<"   "<<block_type[i]<<" ( ";
                    for(int j=0;j<m[i];++j)
                            file_out<<block[i][j]<<" ";
            file_out<<") ( ";
            file_out<<grid[i][0]<<' '<<grid[i][1]<<' '<<grid[i][2]<<" ) ";
            file_out<<grade_type[i]<<" ( ";
            file_out<<grade[i][0]<<' '<<grade[i][1]<<' '<<grade[i][2]<<" )\n";
    }
    file_out<<");\n";
}


//testing example:
int main()
{       
    int block[6][9];
    for(int i=0; i<6;++i) 
            for(int j=0; i<9;++j)
                    block[i][j] = i*j;

    int grid[6][3];
    for(int i=0; i<6;++i)
            for(int j=0; i<3;++j)
                    block[i][j] = i*j;


    int grade[6][3];
    for(int i=0; i<6;++i) 
            for(int j=0; i<3;++j)
                    block[i][j] = i*j;

    string grade_type[6] = {"simpleGrading"};
    string block_type[6] = {"hex"};
    int m[6] = {8};
    int n_blocks = 6;

    of_write_blocks("name",block_type,block,grid,grade_type,grade,n_blocks,m);
}       

any help is appreciated!任何帮助表示赞赏!

You can't.你不能。 Multidimensional arrays are syntactic sugar, and are compiled directly into the code that does manipulations on the array, which is a single memory block.多维 arrays 是语法糖,直接编译到对数组进行操作的代码中,即单个 memory 块。 The dimensions are not passed into the function as parameters or anything like that as part of the array, as things are done in eg Java or C#.尺寸不会作为参数或任何类似的东西作为数组的一部分传递到 function 中,就像在 Java 或 C# 中所做的那样。

If you need the dimensions of the array in your function, you'll need to just accept a pointer to the first element of the array, and the dimensions, and do the multiplies and adds to get the right index yourself.如果您需要 function 中数组的维度,您只需要接受指向数组第一个元素的指针和维度,然后进行乘法和加法以自己获得正确的索引。

Alternately, use something like a std::vector<std::vector<block>> , which pass the dimensions as part of the object, rather than a built in array.或者,使用类似std::vector<std::vector<block>>的东西,它将维度作为 object 的一部分而不是内置数组传递。

If you have Boost installed, check out Boost Multi-Array .如果您安装了 Boost,请查看Boost Multi-Array

For clarity I removed all the irrelevant code from your example.为清楚起见,我从您的示例中删除了所有不相关的代码。

#include <iostream>
#include <fstream>

using namespace std;

void of_write_blocks(int **block, int bh, int bw){

  for(int i = 0; i < bh; ++i)
    for(int j = 0; j < bw; ++j)
      cout << block[i][j] << " ";
  cout << endl;
}

int main(){       

  int bh, bw;
  cin >> bh >> bw;

  int** block;
  block = new int*[bh];
  for(int k = 0; k < bh; k++)
    block[k] = new int[bw];

  // initialize the array
  for(int i = 0; i < bh; i++)
    for(int j = 0; j < bw; j++)
      block[i][j] = (i*bw) + j;

  of_write_blocks( block, bh, bw);
}       

In the main we are creating a 2D array and initializing it.我们主要是创建一个二维数组并对其进行初始化。 Then we pass it to of_write_block, which prints the array.然后我们将它传递给 of_write_block,它会打印数组。 Is that what you wanted to do?那是你想做的吗?

Why can't use a reference of array.为什么不能使用数组的引用。 See below example:请参见下面的示例:

char c[10];
int i[10][20];
double d[10][20][30];

Write a wrapper function like this:像这样编写一个包装器function:

template<typename T, int SIZE>
void Array (T (&a)[SIZE])
{}
template<typename T, int SIZE1, int SIZE2>
void Array (T (&a)[SIZE1][SIZE2])
{}
template<typename T, int SIZE1, int SIZE2, int SIZE3>
void Array (T (&a)[SIZE1][SIZE2][SIZE3])
{}

This is just an example to demonstrate the syntax which will elegantly receive the array without any copying and also avoids confusing pointers.这只是一个示例,用于演示无需任何复制即可优雅地接收数组并避免混淆指针的语法。 Also, if you are aware that you are going to use only for int then simply remove the typename and explicitly mention int .此外,如果您知道您将仅用于int ,那么只需删除类型名并明确提及int ie IE

template<int SIZE>
void Array (int (&a)[SIZE]); // explicitly mention int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM