允许作为沃拉斯功能参数

允许作为沃拉斯功能参数

本文介绍了是否c + +允许作为沃拉斯功能参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于code是用于生成幻方在我所使用的VLA功能

 #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");
    }

}

when file saved with extension .cpp ,On compiling it is giving the following error:

When I changed this extension to .c, it worked fine.
What is the reason behind this?
I think VLAs are not allowed in C++, is it right?

NOTE: Check this link regarding VLAs as parameter:
"[*]" parameter of a function

解决方案

You can't use C-style array that way, all but the first extent must be compile-time constant.

What you can do is pass int *magic_square that points to a one-dimensional n*n array, and use a simple index-mapping function to get the linear index of the cell.

You tagged the question as C++, so you should know that

int square[size][size];

is not valid C++ either, though it's valid C99 and some compilers support it through extension.

For C++ I'd suggest to use std::vector<int> vec(size*size) as holder.

这篇关于是否c + +允许作为沃拉斯功能参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 00:43