将整数传递到函数中的数组(不带指针)
Passing integers to arrays within functions (without pointers)
我正在尝试创建一个幻方,它将打印四种不同的网格大小(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之外的任何值被传递到函数中,您将面临未定义的行为。
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”