Let's say I have a function called MyFunction(int myArray[][])
that does some array manipulations.
假设我有一个叫MyFunction的函数(int myArray[][]]),它进行一些数组操作。
If I write the parameter list like that, the compiler will complain that it needs to know the size of the array at compile time. Is there a way to rewrite the parameter list so that I can pass an array with any size to the function?
如果我这样编写参数列表,编译器会抱怨它需要在编译时知道数组的大小。是否有一种方法可以重写参数列表,以便我可以向函数传递任意大小的数组?
My array's size is defined by two static const int
s in a class, but the compiler won't accept something like MyFunction(int myArray[Board::ROWS][Board::COLS])
.
我的数组的大小由类中的两个静态const ints定义,但是编译器不会接受MyFunction(int myArray[Board:::ROWS][Board:::COLS])之类的东西。
What if I could convert the array to a vector and then pass the vector to MyFunction
? Is there a one-line conversion that I can use or do I have to do the conversion manually?
如果我可以把数组转换成一个向量,然后把这个向量传递给MyFunction呢?我是否可以使用单行转换,还是必须手动进行转换?
17 个解决方案
#1
12
In C++ language, multidimensional array declarations must always include all sizes except possibly the first one. So, what you are trying to do is not possible. You cannot declare a parameter of built-in multidimensional array type without explicitly specifying the sizes.
在c++语言中,多维数组声明必须包含除第一个大小之外的所有大小。所以,你想要做的事情是不可能的。如果没有显式地指定大小,则不能声明内置多维数组类型的参数。
If you need to pass a run-time sized multidimensional array to a function, you can forget about using built-in multidimensional array type. One possible workaround here is to use a "simulated" multidimensional array (1D array of pointers to other 1D arrays; or a plain 1D array that simulates multidimensional array through index recalculation).
如果需要将运行时大小的多维数组传递给函数,则可以忘记使用内置的多维数组类型。一种可能的解决方法是使用“模拟的”多维数组(指向其他一维数组的一维指针数组;或者一个普通的一维数组,通过索引重新计算来模拟多维数组)。
#2
11
In C++ use std::vector to model arrays unless you have a specific reason for using an array.
在c++中,使用std::向量到模型数组,除非您有一个使用数组的特定原因。
Example of a 3x2 vector filled with 0's called "myArray" being initialized:
一个填充为0的3x2向量被初始化为“myArray”的例子:
vector< vector<int> > myArray(3, vector<int>(2,0));
Passing this construct around is trivial, and you don't need to screw around with passing length (because it keeps track):
传递这个结构是很简单的,你不需要在传递长度上浪费时间(因为它保持跟踪):
void myFunction(vector< vector<int> > &myArray) {
for(size_t x = 0;x < myArray.length();++x){
for(size_t y = 0;y < myArray[x].length();++y){
cout << myArray[x][y] << " ";
}
cout << endl;
}
}
Alternatively you can iterate over it with iterators:
或者您可以使用迭代器对其进行迭代:
void myFunction(vector< vector<int> > &myArray) {
for(vector< vector<int> >::iterator x = myArray.begin();x != myArray.end();++x){
for(vector<int>::iterator y = x->begin();y != x->end();++y){
cout << *y << " ";
}
cout << endl;
}
}
In C++0x you can use the auto keyword to clean up the vector iterator solution:
在c++ 0x中,您可以使用auto关键字来清理矢量迭代器解决方案:
void myFunction(vector< vector<int> > &myArray) {
for(auto x = myArray.begin();x != myArray.end();++x){
for(auto y = x->begin();y != x->end();++y){
cout << *y << " ";
}
cout << endl;
}
}
And in c++0x for_each becomes viable with lambdas
在c++0x for_each中都可以使用lambdas
void myFunction(vector< vector<int> > &myArray) {
for_each(myArray.begin(), myArray.end(), [](const vector<int> &x){
for_each(x->begin(), x->end(), [](int value){
cout << value << " ";
});
cout << endl;
});
}
Or a range based for loop in c++0x:
或c++0x中基于循环的范围:
void myFunction(vector< vector<int> > &myArray) {
for(auto x : myArray){
for(auto y : *x){
cout << *y << " ";
}
cout << endl;
}
}
*I am not near a compiler right now and have not tested these, please feel free to correct my examples.
*我现在还没有接近编译器,也没有测试过这些,请随时纠正我的例子。
If you know the size of the array at compile time you can do the following (assuming the size is [x][10]):
如果在编译时知道数组的大小,可以执行以下操作(假设大小为[x][10]):
MyFunction(int myArray[][10])
If you need to pass in a variable length array (dynamically allocated or possibly just a function which needs to take different sizes of arrays) then you need to deal with pointers.
如果您需要传入一个可变长度数组(动态分配或可能只是一个需要使用不同大小的数组的函数),那么您需要处理指针。
And as the comments to this answer state:
对于这个答案的评论是:
boost::multiarray may be appropriate since it more efficiently models a multidimensional array. A vector of vectors can have performance implications in critical path code, but in typical cases you will probably not notice an issue.
boost::多阵列可能是合适的,因为它可以更有效地建模多维阵列。向量向量在关键路径代码中可能具有性能影响,但在典型情况下,您可能不会注意到问题。
#3
4
Pass it as a pointer, and take the dimension(s) as an argument.
将其作为指针传递,并将维度作为参数。
void foo(int *array, int width, int height) {
// initialize xPos and yPos
assert(xPos >= 0 && xPos < width);
assert(yPos >= 0 && yPos < height);
int value = array[yPos * width + xPos];
}
This is assuming you have a simple two-dimensional array, like int x[50][50]
.
假设你有一个简单的二维数组,比如int x[50][50]。
#4
3
There are already a set of answers with the most of the common suggestions: using std::vector
, implementing a matrix
class, providing the size of the array in the function argument... I am only going to add yet another solution based on native arrays --note that if possible you should use a higher level abstraction.
已经有一组答案包含了大多数常见的建议:使用std::vector,实现一个矩阵类,在函数参数中提供数组的大小……我只添加另一个基于本机数组的解决方案——注意,如果可能,您应该使用更高级别的抽象。
At any rate:
无论如何:
template <std::size_t rows, std::size_t cols>
void function( int (&array)[rows][cols] )
{
// ...
}
This solution uses a reference to the array (note the &
and the set of parenthesis around array
) instead of using the pass-by-value syntax. This forces the compiler not to decay the array into a pointer. Then the two sizes (which could have been provided as compile time constants can be defined as template arguments and the compiler will deduct the sizes for you.
该解决方案使用对数组的引用(注意数组周围的&和括号),而不是使用按值传递语法。这迫使编译器不要将数组分解为指针。然后这两个大小(可以提供编译时常量,可以将它们定义为模板参数,编译器将为您减去大小。
NOTE: You mention in the question that the sizes are actually static constants you should be able to use them in the function signature if you provide the value in the class declaration:
注意:您在问题中提到,这些大小实际上是静态常量,如果您提供类声明中的值,您应该能够在函数签名中使用它们:
struct test {
static const int rows = 25;
static const int cols = 80;
};
void function( int *array[80], int rows ) {
// ...
}
Notice that in the signature I prefer to change the double dimension array for a pointer to an array. The reason is that this is what the compiler interprets either way, and this way it is clear that there is no guarantee that the caller of the function will pass an array of exactly 25 lines (the compiler will not enforce it), and it is thus apparent the need for the second integer argument where the caller passes the number of rows.
注意,在签名中,我更喜欢为指向数组的指针更改双维数组。原因是这是编译器解释无论哪种方式,,这种方式显然没有保证函数的调用者会通过整整25行数组(编译器不会执行),并因此明显需要第二个整数参数,调用者传递的行数。
#5
2
You can't pass an arbitrary size like that; the compiler doesn't know how to generate the pointer arithmetic. You could do something like:
不能传递任意大小;编译器不知道如何生成指针算法。你可以这样做:
MyFunction(int myArray[][N])
or you could do:
或者你可以做的:
MyFunction(int *p, int M, int N)
but you'll have to take the address of the first element when you call it (i.e. MyFunction(&arr[0][0], M, N)
.
但是,当你调用第一个元素的地址时(即MyFunction(&arr[0][0], M, N))。
You can get round all of these problems in C++ by using a container class; std::vector
would be a good place to start.
通过使用容器类,可以在c++中解决所有这些问题;向量将是一个很好的起点。
#6
2
The compiler is complaining because it needs to know the size of the all but the first dimension to be able to address an element in the array. For instance, in the following code:
编译器会抱怨,因为它需要知道除第一个维度之外的所有维度的大小,才能处理数组中的一个元素。例如,在下面的代码中:
int array[M][N];
// ...
array[i][j] = 0;
To address the element, the compiler generates something like the following:
为了处理元素,编译器生成如下内容:
*(array+(i*N+j)) = 0;
Therefore, you need to re-write your signature like this:
因此,您需要重新编写您的签名如下:
MyFunction(int array[][N])
in which case you will be stuck with a fixed dimension, or go with a more general solution such as a (custom) dynamic 2D array class or a vector<vector<int> >
.
在这种情况下,您将陷入一个固定的维度,或者使用更通用的解决方案,例如(自定义的)动态2D数组类或向量
#7
1
-
Use a
vector<vector<int> >
(this would be cheating if underlying storage was not guaranteed to be contiguous).使用向量
>(如果底层存储不保证是连续的,这将是作弊)。 -
Use a pointer to
element-of-array
(int*
) and asize
(M*N
) parameter. Here be dragons.使用数组元素指针(int*)和大小(M*N)参数。这里是龙。
#8
1
First, lets see why compiler is complaining.
首先,让我们看看为什么编译器会抱怨。
If an array is defined as int arr[ ROWS ][ COLS ];
then any array notation arr[ i ][ j ]
can be translated to pointer notation as
如果数组定义为int arr[ROWS][COLS];那么任何数组符号arr[i][j]都可以翻译为指针符号
*( arr + i * COLS + j )
Observe that the expression requires only COLS
, it does not require ROWS
. So, the array definition can be written equivalently as
注意表达式只需要COLS,不需要行。数组定义可以写成
int arr [][ COLS ];
But, missing the second dimension is not acceptable. For little more details, read here.
但是,忽略第二个维度是不可接受的。更多细节,请阅读这里。
Now, on your question:
现在,你的问题:
Is there a way to rewrite the parameter list so that I can pass an array with any size to the function?
是否有一种方法可以重写参数列表,以便我可以向函数传递任意大小的数组?
Yes, perhaps you can use a pointer, e.g. MyFunction( int * arr );
. But, think about it, how would MyFunction()
know where to stop accessing the array? To solve that you would need another parameter for the length of the array, e.g. MyFunction( int * arr, size_t arrSize );
是的,也许你可以用一个指针,例如:MyFunction(int * arr);但是,想一想,MyFunction()如何知道停止访问数组的位置呢?要解决这个问题,需要为数组的长度提供另一个参数,例如MyFunction(int * arr, size_t arrSize);
#9
1
Yes: MyFunction(int **myArray);
是的:MyFunction(int * * myArray);
Careful, though. You'd better know what you're doing. This will only accept an array of int pointers.
不过,小心。你最好知道你在做什么。这将只接受一个int指针数组。
Since you're trying to pass an array of arrays, you'll need a constant expression as one of the dimentions:
由于您试图传递数组,所以需要一个常量表达式作为维度之一:
MyFunction(int myArray[][COLS]);
MyFunction(int myArray[][关口]);
You'll need to have COLS
at compile time.
编译时需要有COLS。
I suggest using a vector instead.
我建议用向量代替。
#10
0
Pass a pointer and do the indexing yourself or use a Matrix class instead.
传递一个指针,自己做索引,或者使用一个矩阵类代替。
#11
0
yes - just pass it as pointer(s):
是的——只是作为指针传递:
MyFunction(int** someArray)
The downside is that you'll probably need to pas the array's lengths as well
缺点是您可能还需要检查数组的长度
#12
0
Use MyFunction(int *myArray[])
If you use MyFunction(int **myArray)
an pass int someArray[X][Y]
, the program will crash.
EDIT: Don't use the first line, it's explained in comments.
使用MyFunction(int *myArray[])如果您使用MyFunction(int **myArray),则该程序将崩溃。编辑:不要使用第一行,它是在注释中解释的。
#13
0
I don't know about C++, but the C99 standard introduced variable length arrays.
我不知道c++,但是C99标准引入了可变长度数组。
So this would work in a compiler that supports C99:
这在支持C99的编译器中是可行的
void func(int rows, int cols, double[rows][cols] matrix) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
printf("%f", matrix[r][c]);
}
}
}
Note that the size arguments come before the array. Really, only the number of columns has to be known at compile time, so this would be valid as well:
注意,size参数在数组之前。实际上,在编译时只需要知道列的数量,所以这也是有效的:
void func(int rows, int cols, double[][cols] matrix)
For three or more dimensions, all but the first dimension must have known sizes. The answer ArunSaha linked to explains why.
对于三个或多个维度,除第一个维度外,所有维度都必须具有已知的大小。阿龙萨哈的回答解释了其中的原因。
Honestly, I don't know whether C++ supports variable-length arrays, so this may or may not work. In either case, you may also consider encapsulating your array in some sort of matrix class.
老实说,我不知道c++是否支持可变长度的数组,所以这可能有用,也可能没用。无论哪种情况,您都可以考虑将数组封装到某种类型的矩阵类中。
EDIT: From your edit, it looks like C++ may not support this feature. A matrix class is probably the way to go. (Or std::vector if you don't mind that the memory may not be allocated contiguously.)
编辑:从您的编辑,看起来c++可能不支持这个特性。矩阵类可能是一种方法。(或std::vector,如果您不介意内存可能不被连续分配的话。)
#14
0
Don't pass an array, which is an implementation detail. Pass the Board
不要传递数组,这是实现细节。通过董事会
MyFunction(Board theBoard)
{
...
}
#15
0
In C++0x, you can use std::initializer_list<...>
to accomplish this:
在c++ 0x中,可以使用std::initializer_list<…>来完成:
MyFunction(std::initializer_list<std::initializer_list<int>> myArray);
and use it (I presume) like this (with the range based for syntax):
使用它(我假设)像这样(基于语法的范围):
for (const std::initializer_list<int> &subArray: myArray)
{
for (int value: subArray)
{
// fun with value!
}
}
#16
0
in reality my array's size is defined by two
static const int
s in a class, but the compiler won't accept something likeMyFunction(int myArray[Board::ROWS][Board::COLS])
.实际上,我的数组的大小是由类中的两个静态const ints定义的,但是编译器不会接受类似MyFunction(int myArray[Board::ROWS][Board::COLS])之类的东西。
That's strange, it works perfectly fine for me:
这很奇怪,对我来说很好:
struct Board
{
static const int ROWS = 6;
static const int COLS = 7;
};
void MyFunction(int myArray[Board::ROWS][Board::COLS])
{
}
Maybe ROWS and COLS are private? Can you show us some code?
也许行和COLS是私有的?你能给我们看一些代码吗?
#17
-1
In C++, using the inbuilt array types is instant fail. You could use a boost::/std:: array of arrays or vector of arrays. Primitive arrays are not up to any sort of real use
在c++中,使用内置数组类型是立即失败。您可以使用boost::/std::数组的数组或数组的向量。原始数组没有任何实际用途
#1
12
In C++ language, multidimensional array declarations must always include all sizes except possibly the first one. So, what you are trying to do is not possible. You cannot declare a parameter of built-in multidimensional array type without explicitly specifying the sizes.
在c++语言中,多维数组声明必须包含除第一个大小之外的所有大小。所以,你想要做的事情是不可能的。如果没有显式地指定大小,则不能声明内置多维数组类型的参数。
If you need to pass a run-time sized multidimensional array to a function, you can forget about using built-in multidimensional array type. One possible workaround here is to use a "simulated" multidimensional array (1D array of pointers to other 1D arrays; or a plain 1D array that simulates multidimensional array through index recalculation).
如果需要将运行时大小的多维数组传递给函数,则可以忘记使用内置的多维数组类型。一种可能的解决方法是使用“模拟的”多维数组(指向其他一维数组的一维指针数组;或者一个普通的一维数组,通过索引重新计算来模拟多维数组)。
#2
11
In C++ use std::vector to model arrays unless you have a specific reason for using an array.
在c++中,使用std::向量到模型数组,除非您有一个使用数组的特定原因。
Example of a 3x2 vector filled with 0's called "myArray" being initialized:
一个填充为0的3x2向量被初始化为“myArray”的例子:
vector< vector<int> > myArray(3, vector<int>(2,0));
Passing this construct around is trivial, and you don't need to screw around with passing length (because it keeps track):
传递这个结构是很简单的,你不需要在传递长度上浪费时间(因为它保持跟踪):
void myFunction(vector< vector<int> > &myArray) {
for(size_t x = 0;x < myArray.length();++x){
for(size_t y = 0;y < myArray[x].length();++y){
cout << myArray[x][y] << " ";
}
cout << endl;
}
}
Alternatively you can iterate over it with iterators:
或者您可以使用迭代器对其进行迭代:
void myFunction(vector< vector<int> > &myArray) {
for(vector< vector<int> >::iterator x = myArray.begin();x != myArray.end();++x){
for(vector<int>::iterator y = x->begin();y != x->end();++y){
cout << *y << " ";
}
cout << endl;
}
}
In C++0x you can use the auto keyword to clean up the vector iterator solution:
在c++ 0x中,您可以使用auto关键字来清理矢量迭代器解决方案:
void myFunction(vector< vector<int> > &myArray) {
for(auto x = myArray.begin();x != myArray.end();++x){
for(auto y = x->begin();y != x->end();++y){
cout << *y << " ";
}
cout << endl;
}
}
And in c++0x for_each becomes viable with lambdas
在c++0x for_each中都可以使用lambdas
void myFunction(vector< vector<int> > &myArray) {
for_each(myArray.begin(), myArray.end(), [](const vector<int> &x){
for_each(x->begin(), x->end(), [](int value){
cout << value << " ";
});
cout << endl;
});
}
Or a range based for loop in c++0x:
或c++0x中基于循环的范围:
void myFunction(vector< vector<int> > &myArray) {
for(auto x : myArray){
for(auto y : *x){
cout << *y << " ";
}
cout << endl;
}
}
*I am not near a compiler right now and have not tested these, please feel free to correct my examples.
*我现在还没有接近编译器,也没有测试过这些,请随时纠正我的例子。
If you know the size of the array at compile time you can do the following (assuming the size is [x][10]):
如果在编译时知道数组的大小,可以执行以下操作(假设大小为[x][10]):
MyFunction(int myArray[][10])
If you need to pass in a variable length array (dynamically allocated or possibly just a function which needs to take different sizes of arrays) then you need to deal with pointers.
如果您需要传入一个可变长度数组(动态分配或可能只是一个需要使用不同大小的数组的函数),那么您需要处理指针。
And as the comments to this answer state:
对于这个答案的评论是:
boost::multiarray may be appropriate since it more efficiently models a multidimensional array. A vector of vectors can have performance implications in critical path code, but in typical cases you will probably not notice an issue.
boost::多阵列可能是合适的,因为它可以更有效地建模多维阵列。向量向量在关键路径代码中可能具有性能影响,但在典型情况下,您可能不会注意到问题。
#3
4
Pass it as a pointer, and take the dimension(s) as an argument.
将其作为指针传递,并将维度作为参数。
void foo(int *array, int width, int height) {
// initialize xPos and yPos
assert(xPos >= 0 && xPos < width);
assert(yPos >= 0 && yPos < height);
int value = array[yPos * width + xPos];
}
This is assuming you have a simple two-dimensional array, like int x[50][50]
.
假设你有一个简单的二维数组,比如int x[50][50]。
#4
3
There are already a set of answers with the most of the common suggestions: using std::vector
, implementing a matrix
class, providing the size of the array in the function argument... I am only going to add yet another solution based on native arrays --note that if possible you should use a higher level abstraction.
已经有一组答案包含了大多数常见的建议:使用std::vector,实现一个矩阵类,在函数参数中提供数组的大小……我只添加另一个基于本机数组的解决方案——注意,如果可能,您应该使用更高级别的抽象。
At any rate:
无论如何:
template <std::size_t rows, std::size_t cols>
void function( int (&array)[rows][cols] )
{
// ...
}
This solution uses a reference to the array (note the &
and the set of parenthesis around array
) instead of using the pass-by-value syntax. This forces the compiler not to decay the array into a pointer. Then the two sizes (which could have been provided as compile time constants can be defined as template arguments and the compiler will deduct the sizes for you.
该解决方案使用对数组的引用(注意数组周围的&和括号),而不是使用按值传递语法。这迫使编译器不要将数组分解为指针。然后这两个大小(可以提供编译时常量,可以将它们定义为模板参数,编译器将为您减去大小。
NOTE: You mention in the question that the sizes are actually static constants you should be able to use them in the function signature if you provide the value in the class declaration:
注意:您在问题中提到,这些大小实际上是静态常量,如果您提供类声明中的值,您应该能够在函数签名中使用它们:
struct test {
static const int rows = 25;
static const int cols = 80;
};
void function( int *array[80], int rows ) {
// ...
}
Notice that in the signature I prefer to change the double dimension array for a pointer to an array. The reason is that this is what the compiler interprets either way, and this way it is clear that there is no guarantee that the caller of the function will pass an array of exactly 25 lines (the compiler will not enforce it), and it is thus apparent the need for the second integer argument where the caller passes the number of rows.
注意,在签名中,我更喜欢为指向数组的指针更改双维数组。原因是这是编译器解释无论哪种方式,,这种方式显然没有保证函数的调用者会通过整整25行数组(编译器不会执行),并因此明显需要第二个整数参数,调用者传递的行数。
#5
2
You can't pass an arbitrary size like that; the compiler doesn't know how to generate the pointer arithmetic. You could do something like:
不能传递任意大小;编译器不知道如何生成指针算法。你可以这样做:
MyFunction(int myArray[][N])
or you could do:
或者你可以做的:
MyFunction(int *p, int M, int N)
but you'll have to take the address of the first element when you call it (i.e. MyFunction(&arr[0][0], M, N)
.
但是,当你调用第一个元素的地址时(即MyFunction(&arr[0][0], M, N))。
You can get round all of these problems in C++ by using a container class; std::vector
would be a good place to start.
通过使用容器类,可以在c++中解决所有这些问题;向量将是一个很好的起点。
#6
2
The compiler is complaining because it needs to know the size of the all but the first dimension to be able to address an element in the array. For instance, in the following code:
编译器会抱怨,因为它需要知道除第一个维度之外的所有维度的大小,才能处理数组中的一个元素。例如,在下面的代码中:
int array[M][N];
// ...
array[i][j] = 0;
To address the element, the compiler generates something like the following:
为了处理元素,编译器生成如下内容:
*(array+(i*N+j)) = 0;
Therefore, you need to re-write your signature like this:
因此,您需要重新编写您的签名如下:
MyFunction(int array[][N])
in which case you will be stuck with a fixed dimension, or go with a more general solution such as a (custom) dynamic 2D array class or a vector<vector<int> >
.
在这种情况下,您将陷入一个固定的维度,或者使用更通用的解决方案,例如(自定义的)动态2D数组类或向量
#7
1
-
Use a
vector<vector<int> >
(this would be cheating if underlying storage was not guaranteed to be contiguous).使用向量
>(如果底层存储不保证是连续的,这将是作弊)。 -
Use a pointer to
element-of-array
(int*
) and asize
(M*N
) parameter. Here be dragons.使用数组元素指针(int*)和大小(M*N)参数。这里是龙。
#8
1
First, lets see why compiler is complaining.
首先,让我们看看为什么编译器会抱怨。
If an array is defined as int arr[ ROWS ][ COLS ];
then any array notation arr[ i ][ j ]
can be translated to pointer notation as
如果数组定义为int arr[ROWS][COLS];那么任何数组符号arr[i][j]都可以翻译为指针符号
*( arr + i * COLS + j )
Observe that the expression requires only COLS
, it does not require ROWS
. So, the array definition can be written equivalently as
注意表达式只需要COLS,不需要行。数组定义可以写成
int arr [][ COLS ];
But, missing the second dimension is not acceptable. For little more details, read here.
但是,忽略第二个维度是不可接受的。更多细节,请阅读这里。
Now, on your question:
现在,你的问题:
Is there a way to rewrite the parameter list so that I can pass an array with any size to the function?
是否有一种方法可以重写参数列表,以便我可以向函数传递任意大小的数组?
Yes, perhaps you can use a pointer, e.g. MyFunction( int * arr );
. But, think about it, how would MyFunction()
know where to stop accessing the array? To solve that you would need another parameter for the length of the array, e.g. MyFunction( int * arr, size_t arrSize );
是的,也许你可以用一个指针,例如:MyFunction(int * arr);但是,想一想,MyFunction()如何知道停止访问数组的位置呢?要解决这个问题,需要为数组的长度提供另一个参数,例如MyFunction(int * arr, size_t arrSize);
#9
1
Yes: MyFunction(int **myArray);
是的:MyFunction(int * * myArray);
Careful, though. You'd better know what you're doing. This will only accept an array of int pointers.
不过,小心。你最好知道你在做什么。这将只接受一个int指针数组。
Since you're trying to pass an array of arrays, you'll need a constant expression as one of the dimentions:
由于您试图传递数组,所以需要一个常量表达式作为维度之一:
MyFunction(int myArray[][COLS]);
MyFunction(int myArray[][关口]);
You'll need to have COLS
at compile time.
编译时需要有COLS。
I suggest using a vector instead.
我建议用向量代替。
#10
0
Pass a pointer and do the indexing yourself or use a Matrix class instead.
传递一个指针,自己做索引,或者使用一个矩阵类代替。
#11
0
yes - just pass it as pointer(s):
是的——只是作为指针传递:
MyFunction(int** someArray)
The downside is that you'll probably need to pas the array's lengths as well
缺点是您可能还需要检查数组的长度
#12
0
Use MyFunction(int *myArray[])
If you use MyFunction(int **myArray)
an pass int someArray[X][Y]
, the program will crash.
EDIT: Don't use the first line, it's explained in comments.
使用MyFunction(int *myArray[])如果您使用MyFunction(int **myArray),则该程序将崩溃。编辑:不要使用第一行,它是在注释中解释的。
#13
0
I don't know about C++, but the C99 standard introduced variable length arrays.
我不知道c++,但是C99标准引入了可变长度数组。
So this would work in a compiler that supports C99:
这在支持C99的编译器中是可行的
void func(int rows, int cols, double[rows][cols] matrix) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
printf("%f", matrix[r][c]);
}
}
}
Note that the size arguments come before the array. Really, only the number of columns has to be known at compile time, so this would be valid as well:
注意,size参数在数组之前。实际上,在编译时只需要知道列的数量,所以这也是有效的:
void func(int rows, int cols, double[][cols] matrix)
For three or more dimensions, all but the first dimension must have known sizes. The answer ArunSaha linked to explains why.
对于三个或多个维度,除第一个维度外,所有维度都必须具有已知的大小。阿龙萨哈的回答解释了其中的原因。
Honestly, I don't know whether C++ supports variable-length arrays, so this may or may not work. In either case, you may also consider encapsulating your array in some sort of matrix class.
老实说,我不知道c++是否支持可变长度的数组,所以这可能有用,也可能没用。无论哪种情况,您都可以考虑将数组封装到某种类型的矩阵类中。
EDIT: From your edit, it looks like C++ may not support this feature. A matrix class is probably the way to go. (Or std::vector if you don't mind that the memory may not be allocated contiguously.)
编辑:从您的编辑,看起来c++可能不支持这个特性。矩阵类可能是一种方法。(或std::vector,如果您不介意内存可能不被连续分配的话。)
#14
0
Don't pass an array, which is an implementation detail. Pass the Board
不要传递数组,这是实现细节。通过董事会
MyFunction(Board theBoard)
{
...
}
#15
0
In C++0x, you can use std::initializer_list<...>
to accomplish this:
在c++ 0x中,可以使用std::initializer_list<…>来完成:
MyFunction(std::initializer_list<std::initializer_list<int>> myArray);
and use it (I presume) like this (with the range based for syntax):
使用它(我假设)像这样(基于语法的范围):
for (const std::initializer_list<int> &subArray: myArray)
{
for (int value: subArray)
{
// fun with value!
}
}
#16
0
in reality my array's size is defined by two
static const int
s in a class, but the compiler won't accept something likeMyFunction(int myArray[Board::ROWS][Board::COLS])
.实际上,我的数组的大小是由类中的两个静态const ints定义的,但是编译器不会接受类似MyFunction(int myArray[Board::ROWS][Board::COLS])之类的东西。
That's strange, it works perfectly fine for me:
这很奇怪,对我来说很好:
struct Board
{
static const int ROWS = 6;
static const int COLS = 7;
};
void MyFunction(int myArray[Board::ROWS][Board::COLS])
{
}
Maybe ROWS and COLS are private? Can you show us some code?
也许行和COLS是私有的?你能给我们看一些代码吗?
#17
-1
In C++, using the inbuilt array types is instant fail. You could use a boost::/std:: array of arrays or vector of arrays. Primitive arrays are not up to any sort of real use
在c++中,使用内置数组类型是立即失败。您可以使用boost::/std::数组的数组或数组的向量。原始数组没有任何实际用途