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

时间:2019-12-09 13:34:37

标签: c global-variables

我想将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]);
....
}

1 个答案:

答案 0 :(得分: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;//indices used to dimension arrays can be global scope
int main(int argc, char *argv[])command line args contain two integer values
{
    N = atoi(argv[1]); //use argv[1] & [2]. ( [0] is name of program    )
    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(int numStrings, int 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;
}

请注意,此处创建的字符串需要释放。