Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将整数传递给函数内的数组(不带指针)_C++_Arrays_Function_Constants - Fatal编程技术网

C++ 将整数传递给函数内的数组(不带指针)

C++ 将整数传递给函数内的数组(不带指针),c++,arrays,function,constants,C++,Arrays,Function,Constants,我正在尝试创建一个魔方,可以打印四种不同的网格大小(5x5、7x7、9x9、15x15)。我遇到的错误是函数中的数组magsquare告诉我它需要一个常量整数。(我不能使用指针)这是一个类赋值 #include <iostream> #include <iomanip> using namespace std; void magicSquare(int n){ int magsquare[n][n] = { 0 }; /*THIS is the error wit

我正在尝试创建一个魔方,可以打印四种不同的网格大小(5x5、7x7、9x9、15x15)。我遇到的错误是函数中的数组magsquare告诉我它需要一个常量整数。(我不能使用指针)这是一个类赋值

#include <iostream>
#include <iomanip>
using namespace std;

void magicSquare(int n){
int magsquare[n][n] = { 0 };    /*THIS is the error with [n][n]*/

int gridsize = n * n;
int row = 0;
int col = n / 2;

for (int i = 1; i <= gridsize; ++i)
{
    magsquare[row][col] = i;

    row--;
    col++;

    if (i%n == 0)
    {
        row += 2;
        --col;
    }
    else
    {
        if (col == n)
            col -= n;
        else if (row < 0)
            row += n;
    }
}
for (int i = 0; i < n; i++){
    for (int j = 0; j < n; j++){
        cout << setw(3) << right << magsquare[i][j];
    }
    cout << endl;

}

}
int main(){
    int n = 5;
    magicSquare(n);
    return 0;
}
#包括
#包括
使用名称空间std;
无效magicSquare(内部n){
int magsquare[n][n]={0};/*这是[n][n]的错误*/
int gridsize=n*n;
int行=0;
int col=n/2;

对于(int i=1;i ),失败是因为标准C++不能在栈中分配动态大小的数组,正如您正试图做的那样。
int magsquare[n][n];
magicSquare
而言,
n
仅在运行时已知,对于要在堆栈上分配的数组,其大小必须在编译时已知

使用15 x 15阵列

int magsquare[15][15];
只要你知道这是你需要的最大的,你就应该没事了

备选方案(您已经说过不能使用)

  • 使用
    new
    声明所需维度的2d数组。(但要记住删除它)
  • 使用
    std::vector

最好添加一个检查,检查超过15或低于1的n个值是否被拒绝,否则如果将1-15之外的任何值传递到函数中,您将面临未定义的行为。

请放松,改用
std::vector
。()我不能在代码中使用向量或指针:/嘿!我从来没有对OP无礼过。称他/她的老师为不称职的tw*t当然不会使该评论无效(这只是告诉了我在日常工作中必须忍受的事实)作为旁注,有人能解释一下为什么他的代码适合我吗?@Wolfgang.Finkbeiner,因为有些编译器支持(作为专有扩展)根据堆栈上的其他变量值在堆栈上分配数组大小。但这不是标准c++/c所能保证的。非常感谢。这是一个非常简单的解决方案。没有问题。如果你想得到答案,你可以接受。你会发现,使用c/c++时,一点软糖通常可以让事情变得简单得多。