2017-04-04 142 views
-3

C編程警告:控制到達非void函數結束[-Wreturn型]}

代碼:

struct battleship makeShip (int size, int pos) 
{ 
    int i, j; 
    int* body; 
    body = (int*) malloc (size * sizeof(int)); 
    for (i = pos; i < (pos + size); i++){ 
     for (j=0; j < size; j++){ 
      body[j] = 1; 
     } 
    } 
} 

不知道,如果我嘗試並添加回報是什麼原因造成的錯誤0 ;我得到:

錯誤:從不兼容的結果函數返回'int' 類型'struct battleship' return 0;

+0

你不能有不同的返回類型。如果函數類型是int,那麼只有你可以返回int。如果你使用其他類型,它會抱怨。 – LethalProgrammer

+0

甚至沒有在你的函數中定義的「struct battleship」變量,所以不確定你爲什麼要返回一個 –

回答

0

你將不得不返回一個戰列艦結構。

如果您不需要任何回報,只是改變:

struct battleship 

有:

void 

含義函數返回什麼。

考慮到你在這裏爲某些東西分配了一些內存,你可能想返回body的地址,這是一個指向int類型的指針。
在這種情況下,你的函數應該這樣開始:

int * makeShip(int size, int pos) 
0
struct battleship makeShip (int size, int pos) 
{ 
    int i, j; 
    int* body; 
    body = (int*) malloc (size * sizeof(int)); 
    for (i = pos; i < (pos + size); i++){ 
     for (j=0; j < size; j++){ 
      body[j] = 1; 
     } 
    } 
    struct battleship ship; 
    ship.body = body; 
    ship.size = size; 
    ship.pos = pos; 
    return ship; 

}

相關問題