我写了以下代码,但它显示错误
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);
}
我试图使用全局变量传递可变大小的多维数组。我不想在这里使用矢量。
你已经收到了解释原因的答案。我提供这个只是为了完整性C ++。就个人而言,虽然我不明白你为什么要避免向量,但它们确实提供了更直观或令人愉悦的解决方案。在处理向量的函数内部,您可以随时查阅std::vector<>.size()
以确保您保持在bounds或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
}
首先C ++没有可变长度数组,所以你应该使用int s[n][n]={0};
而不是std::vector<std::vector<int>> s(10,std::vector<int>(10));
其次如何将2D数组传递给函数,
void a(std::vector<int> **s,int rows, int cols){
cout<<"1";
/* stuff with 2D array */
}
数组大小必须是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);
}
你不能。你的函数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);
...