将一个函数中声明的数组用于另一个函数

Using an array declared in one function to another function

本文关键字:函数 声明 数组 用于 另一个 一个      更新时间:2023-10-16

我目前被困在编程的一部分上。我创建了一个函数来获取 2D 数组的行数和列数,然后用输入文件中的信息填充该数组。

我现在需要在另一个函数中使用该数组来显示该数组。这是当前代码。此外,我无法以任何方式修改函数定义,因此我很确定我必须使用指针,而这些指针确实让我感到困惑。

有人可以澄清或帮助吗?

void populateWorld (const char * file)
{
int numchar = 0;
int numline = 0;
char a;
ifstream inFile;
inFile.open("glider_gun_fight.txt");
inFile.get(a);
while(inFile)
{
    while(inFile && a != 'n')
    {
        numchar = numchar + 1;
        inFile.get(a);
    }
    numline = numline + 1;
    inFile.get(a);
}
ROWS = numline;
COLUMNS = numchar / numline;
inFile.close();
inFile.open("glider_gun_fight.txt");

char gameBoard[ROWS][COLUMNS];
for(int r = 0; r < ROWS; r++)
{
    for(int c = 0; c < COLUMNS; c++)
    {
        inFile >> gameBoard [r][c];
    }
}
inFile.close();
}
//This function outputs the grid for current generation (add high level 
//description of your implementation logic) 
void showWorld ()
{
for(int r = 0; r < ROWS; r++)
{
    for(int c = 0; c < COLUMNS; c++)
    {
        cout << gameBoard [r][c];
    }
    cout << endl;
}
}

在不更改函数声明的情况下,剩下的唯一可能性是全局变量:

char **gameBoard;
void populateWorld (const char * file) {
    //...
    //char gameBoard[ROWS][COLUMNS]; //Not local anymore, instead allocate dynamically:
    gameBoard = new char*[ROWS];
    for(int r = 0; r < ROWS; r++)
    {
        gameBoard[r] = new char[COLUMNS];
        for(int c = 0; c < COLUMNS; c++)
        {
            inFile >> gameBoard [r][c];
        }
    }
    //...
}

然后另一个函数按原样工作。但是,应该避免全局变量。(尽管ROWSCOLUMNS似乎已经是全球性的,所以多一个不会造成太大伤害。

不要忘记在不再需要时再次释放分配的内存delete[]

正如我所说,C++还有其他方法,例如stringgetlinevector,真正应该使用哪种方法。

如果不更改函数声明,则无法在外部世界中传递在此函数中创建的数组:)还要考虑到您的函数C++不合规。在C++数组的大小中,ahall 是编译时的常量表达式。如果文件包含制表符,则其输出可能与您预期的不同。