2016-12-03 30 views
0

返回一個指向2-d陣列我知道這個問題已經被問hereherehere和許多次,但有什麼地方還沒有成型。我試圖讓在C卡諾圖求解器,我想我的功能之一傳遞一個二維數組回到主功能,所以這裏是我的程序:從C函數

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]){ 
       ^

我的問題是,我可以解決這些警告?並且將這些警告引起任何問題,將來我不知道他們爲什麼出現

也不要,我是一個新手,所以請不要生我的惡劣,如果這個問題沒有正確地問..

謝謝。

+0

是的,feedOnes只是一個程序,打印輸出..沒有其他 – sameer

+0

你讀過可能的重複嗎?你不能返回一個指向數組的指針。通常,您可以根據需要創建數組,並將其作爲指針傳遞給函數,在您創建的範圍內對數組執行任何操作,包括在同一範圍內調用的函數。但返回它是一個問題,因爲它的分配方式會在超出範圍時導致重新分配。 –

+0

你可以嘗試做真正在鏈接中所建議的事情「在這裏,這裏和這裏」 –

回答

0

數組grid[][]setMap()函數的本地類。一旦該函數返回,該變量不再可用並且超出範圍。都在堆棧存儲器聲明局部變量。

爲了這樣的事情工作,你將需要分配解除分配的使用malloc()free()功能內存分別調用。

參考此鏈接爲澄清堆棧VS堆內存:

What and where are the stack and heap?

參考此鏈接爲作用域用C

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

快樂編程!