在c ++中传递函数中可变大小的多维数组

时间:2018-02-27 16:39:00

标签: c++ arrays

我编写了以下代码,但它显示错误

use of parameter outside function body before ‘]’ token

代码是

#include <iostream>
using namespace std;
int n=10;
void a(int s[n][n])
{
    cout<<"1";
}
int main()
{
    int s[n][n]={0};
    a(s);
}

我正在尝试使用全局变量传递可变大小的多维数组。我不想在这里使用矢量。

4 个答案:

答案 0 :(得分:2)

首先C ++没有可变长度数组,所以你应该使用int s[n][n]={0};而不是std::vector<std::vector<int>> s(10,std::vector<int>(10)); void a(std::vector<int> **s,int rows, int cols){ cout<<"1"; /* stuff with 2D array */ }

其次如何将2D数组传递给函数,

SELECT customer.*,addresses
FROM customer 
LEFT JOIN  (SELECT array_to_json(array_agg(json_build_object('id',address.id,'street_name',address.street_name,'street_number',address.street_number,'zip_code',address.zip_code,'city',address.city))) AS addresses,address.customer_id AS customer_id 
            FROM customer_address AS address 
            GROUP BY address.customer_id) addresses 
ON addresses.customer_id = customer.id    
JOIN customer_address ON customer_address.id = customer.id
WHERE customer_address.street_name LIKE 'Ro%'

答案 1 :(得分:1)

您已收到解释 why 的答案。我提供这个只是为了完整性C ++。就个人而言,虽然我不明白你为什么要避免向量,但它们确实提供了更直观或令人愉悦的解决方案。在处理向量的函数内部,您可以随时查阅std::vector<>.size()以确保您保持在边界内或std::vector<>.at()并捕获在访问越界时引发的异常。不过,您的特定问题也可以通过模板解决。下面是您的代码,略有修改,并附有注释说明。我使用gcc 4.8.5进行了测试:

#include <iostream>
using namespace std;

// Made constant so that the compiler will not complain
// that a non-constant value, at compile time, is being
// used to specify array size.
const int n=10;

// Function template.  Please note, however, this template
// will only auto-gen functions for 2D arrays.
template<int lb>
void a(int s[][lb])
{
    // output the last element to know we're doing this correctly
    // also note that the use of 9 hard-codes this function template
    // to 2D arrays where the first dimension is always, at least, 10
    // elements long!!!!!!
    cout << s[9][lb - 1] << endl;
}

int main()
{
    int s[n][1];
    s[9][0] = 15;
    a<1>(s); // explicitly call template with the size of the last dimension
    a(s); // Call the same function generated from the previous call

    int t[n][2];
    t[9][1] = 17;
    a(t); // compiler implicitly determines the type of function to generate
}

答案 2 :(得分:0)

您的数组大小必须是const。试试这个。

#include <iostream>
using namespace std;
const int n=10;

void a(int s[n][n])
{
    cout<<"1";
}
int main()
{
    int s[n][n]={0};
    a(s);
}

答案 3 :(得分:0)

你做不到。你的函数a()需要知道最后一个维度,即矩阵中每一行的长度。您需要将此作为额外参数传递给您的函数。

void a(int * matrix, int rows, int columns) {
   int row = ...
   int column = ...
   if (row < rows && column < columns) {
      cout << matrix[row*columns + column];
   }
}

int main() {
   ...
   a(&s[0][0], 10);
   ...