簡體   English   中英

從C函數返回指向二維數組的指針

[英]Return a pointer to a 2-D array from a C-function

我知道這個問題在這里這里這里被問很多次了,但是還沒有解決。 我正在嘗試用C語言制作一個卡諾地圖求解器,我希望我的一個函數將2D數組傳遞回主函數,所以這是我的程序:

    typedef char (*arr)[][4];

    int rows;

    int main(void){
      int noVar;
      char *grid;
      printf("Please Enter the number of variables: ");


      scanf("%d",&noVar);
      grid = setMap(noVar);
      feedOnes(grid);
    }

    arr setMap(int noVar){

    rows = pow(2,noVar)/4;
    char grid[rows][4];
    for(int i = 0; i<rows; i++){
        for(int j = 0; j<4; j++){
            grid[i][j]='0';
        }
    }
    printGrid(grid);
    return &grid;
}

這會給我一個4條警告,提示它目前正在工作:

    In file included from kmap.c:9:
./setMap.h:33:13: warning: address of stack memory associated with local
      variable 'grid' returned [-Wreturn-stack-address]
    return &grid;
            ^~~~
./setMap.h:56:1: warning: control reaches end of non-void function
      [-Wreturn-type]
}
^
kmap.c:16:8: warning: incompatible pointer types assigning to 'char *' from
      'arr' (aka 'char (*)[][4]') [-Wincompatible-pointer-types]
  grid = setMap(noVar);
       ^ ~~~~~~~~~~~~~
kmap.c:17:12: warning: incompatible pointer types passing 'char *' to parameter
      of type 'char (*)[4]' [-Wincompatible-pointer-types]
  feedOnes(grid);
           ^~~~
./setMap.h:36:19: note: passing argument to parameter 'grid' here
int feedOnes(char grid[][4]){
                  ^

我的問題是,我可以解決這些警告嗎? 這些警告將來會不會引起任何問題,因為我不知道為什么會出現

另外,我是新手,所以如果這個問題沒有正確提出,請不要對我嚴厲。

謝謝。

數組grid[][]對於setMap()函數而言是局部的。 此函數返回后,該變量將不再可用且不在范圍內。 局部變量堆棧存儲器中聲明。

為了使類似的東西起作用,您將需要分別使用malloc()free()函數調用從堆中 分配釋放內存。

請參考此鏈接以獲取有關堆棧與堆內存的說明:

什么是堆棧和堆?

請參閱此鏈接以了解C范圍

https://www.tutorialspoint.com/cprogramming/c_scope_rules.htm

編程愉快!

暫無
暫無

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

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