簡體   English   中英

如何通過從函數中取值來聲明全局變量

[英]How to declare global variable by taking value from function

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

……那么我該如何實現呢?

C99及更高版本中,您可以使用VLA來設置數組索引的大小,但 VLA 僅限於local scope ,因此使用此方法,這些在全局范圍內都不合法:

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

請注意,此處創建的字符串需要釋放。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM