2017-04-04 109 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; 

}

相关问题