我正在通过“学习准则”这本艰难的书,并坚持练习19 http://c.learncodethehardway.org/book/ex19.html。我绝望,复制并粘贴了代码,但我仍然遇到错误:
cc -Wall -g ex19.c object.o -o ex19
ex19.c: In function ‘Room_move’:
ex19.c:65:5: warning: ‘return’ with a value, in function returning void
return next;
^
ex19.c: In function ‘Map_move’:
ex19.c:95:10: error: void value not ignored as it ought to be
next = location->_(move)(location, direction);
^
ex19.c: In function ‘Room_attack’:
ex19.c:145:5: warning: initialization from incompatible pointer type
.move = Map_move,
^
ex19.c:145:5: warning: (near initialization for ‘MapProto.move’)
ex19.c:199:5: warning: ‘main’ is normally a non-static function [-Wmain]
int main(int argc, char *argv[])
^
ex19.c:214:1: error: expected declaration or statement at end of input
}
^
ex19.c:214:1: error: expected declaration or statement at end of input
ex19.c:214:1: warning: control reaches end of non-void function [-Wreturn-type]
}
这就是我得到的:
void Room_move(void *self, Direction direction)
{
Room *room = self;
Room *next = NULL;
if(direction == NORTH && room->north) {
printf("You go north, into:\n");
next = room->north;
} else if(direction == SOUTH && room->south) {
printf("You go south, into:\n");
next = room->south;
} else if(direction == EAST && room->east) {
printf("You go east, into:\n");
next = room->east;
} else if(direction == WEST && room->west) {
printf("You go west, into:\n");
next = room->west;
} else {
printf("You can't go that direction.");
next = NULL;
}
if(next) {
next->_(describe)(next);
}
return next;
}
void *Map_move(void *self, Direction direction)
{
Map *map = self;
Room *location = map->location;
Room *next = NULL;
next = location->_(move)(location, direction);
if(next) {
map->location = next;
}
return next;
}
int main(int argc, char *argv[])
{
// simple way to setup the randomness
srand(time(NULL));
// make our map to work with
Map *game = NEW(Map, "The Hall of the Minotaur.");
printf("You enter the ");
game->location->_(describe)(game->location);
while(process_input(game)) {
}
return 0;
}
答案 0 :(得分:3)
这一行:
void Room_move(void *self, Direction direction)
应该是:
void *Room_move(void *self, Direction direction)
您链接的页面就是这种情况,因此您在复制/粘贴代码时搞砸了。
答案 1 :(得分:1)
在指定Room_move()
函数的返回类型时,您错过了指针变量。你需要使用
void* Room_move(void *self, Direction direction)
而不是void Room_move(void *self, Direction direction)
。
void* Room_move()
将返回类型设为void *
,但void Room_move()
实质上意味着返回void
。副作用:
警告:'return'带有一个值,函数返回void
错误:无法忽略void值,因为它应该是
因此,正如您所看到的,void
和void*
不相同。