简体   繁体   中英

How to declare global variable by taking value from function

I wanted to declare N and M as global variable but i need to take N and M value from int main,so how do i make this happen?

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

...so how do i make this happen?

In C99 and beyond you can use a VLA to set the size of the array indices, but VLAs are limited to local scope , so with this method, none of these are legal at global scope:

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

If global scope is a requirement, dynamic allocation is also required:

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;
}

Note that the strings created here need to be freed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM