如何通过从函数中获取值来声明全局变量

问题描述 投票:0回答:1

我想将N和M贴花为全局变量,但我需要从int main中获取N和M值,所以我该如何做到这一点?

#include <stdio.h>
...
int N,M;                            /*
char board[N][N];
char game_board[N][N];                multiple function using  
char (*boardptr)[N]=board;            
char (*game_boardptr)[N]=game_board;                          */
....
int main(int argc,char *argv[])
{
 N = atoi(argv[1]);
 M = atoi(argv[2]);
....
}
c global-variables
1个回答
0
投票

...所以我如何做到这一点?

C99和更高版本中,您可以使用VLA设置数组索引的大小,但是在文件范围内不允许VLA声明,因此使用此方法,不能在以下位置声明所有这些:全球范围:

char board[N][N];
char game_board[N][N];
char (*boardptr)[N]=board;
char (*game_boardptr)[N]=game_board;

如果需要全局范围,则还需要动态分配:

int N, M;
int main(int argc, char *argv[])command line args contain two integer values
{
    N = atoi(argv[1]); //use    
    M = atoi(argv[2]);

    //if global was not a requirement, you could create arrays like this:
    char board[M][N];// VLA - no need to use calloc or malloc
    //no need to free memory when finished using the array, 

    //If global scope is require, this method will work:
    char **board = Create2DStr(N, M);
    ///etc...

    return 0;
}

char ** Create2DStr(ssize_t numStrings, ssize_t maxStrLen)
{
    int i;
    char **a = {0};
    a = calloc(numStrings, sizeof(char *));
    for(i=0;i<numStrings; i++)
    {
      a[i] = calloc(maxStrLen + 1, 1);
    }
    return a;
}
© www.soinside.com 2019 - 2024. All rights reserved.