将整数传递到函数中的数组(不带指针)

Passing integers to arrays within functions (without pointers)

本文关键字:数组 指针 整数 函数      更新时间:2023-10-16

我正在尝试创建一个幻方,它将打印四种不同的网格大小(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;
}

缩进看起来可能不正确,但它是正确的。很抱歉

失败是因为标准C++无法像您尝试的那样在堆栈上分配动态大小的数组。

int magsquare[n][n];

magicSquare而言,n仅在运行时已知,对于要在堆栈上分配的数组,其大小必须在编译时已知。

使用15 x 15阵列。

int magsquare[15][15];

只要你知道这是你所需要的最大的,你就应该没事。

替代品(你已经说过你不能使用)

  • 使用new声明所需维度的二维数组。(不过请记住删除[])
  • 使用std::vector

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