hac*_*cks 0 c c++ arrays function
给定代码用于生成魔术方块,其中我已使用VLA作为函数
create_magic_square(int n,int magic_square [n] [n])
print_magic_square(int n,int magic_square [n] [n])
#include <stdio.h>
void create_magic_square(int n, int magic_square[n][n]);
void print_magic_square(int n, int magic_square[n][n]);
int main()
{
int size;
printf("This program creates a magic square of a specified size");
printf("The size be an odd number between 1 and 99");
printf("Enter the size of magic square: ");
scanf("%d", &size);
if(size%2 == 0 || size < 0 || size > 99)
{
printf("Wrong Entry!!!");
return 0;
}
int square[size][size];
for( int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
square[i][j] = 0;
create_magic_square(size, square);
print_magic_square(size, square);
return 0;
}
void create_magic_square(int n, int magic_square[n][n])
{
int row = 0, col = n/2;
magic_square[row][col] = 1;
while(magic_square[row][col] <= n*n)
{
int new_row = ((row - 1) + n) % n;
int new_col = ((col + 1) + n) % n;
if(magic_square[new_row][new_col] == 0)
{
magic_square[new_row][new_col] = magic_square[row][col] + 1;
row = new_row;
col = new_col;
}
else if(magic_square[new_row][new_col] != 0)
{
magic_square[row + 1][col] = magic_square[row][col] + 1;
row = row + 1;
}
}
}
void print_magic_square(int n, int magic_square[n][n])
{
for( int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
printf("%d ", magic_square[i][j]);
printf("\n\n");
}
}
Run Code Online (Sandbox Code Playgroud)
当文件以扩展名.cpp保存时,在编译它时会出现以下错误:

当我将此扩展名更改为.c时,它工作正常.
这背后的原因是什么?
我认为在C++中不允许使用VLA,是不是?
注意:检查此链接有关VLA作为参数:
为什么使用星号"[*]"而不是函数的VLA数组参数的整数?
你不能用那种方式使用C风格的数组,除了第一个范围以外都必须是编译时常量.
你可以做的是将int *magic_square这些点传递给一维n*n数组,并使用简单的索引映射函数来获得单元格的线性索引.
您将问题标记为C++,因此您应该知道这一点
int square[size][size];
Run Code Online (Sandbox Code Playgroud)
也不是有效的C++,虽然它是有效的C99,一些编译器通过扩展支持它.
对于C++,我建议使用std::vector<int> vec(size*size)作为持有者.