在我的“for循环”中得到一个错误。
程序编译并执行,
但是当我尝试使用case NEW_GAME的代码时:在我的开关语句中,程序‘挂起’然后输出‘分段错误(内核转储)’,我认为这意味着程序试图访问一些内存块,但我不明白为什么会发生这种情况……
我尝试了填充,new_map.itemsindex.type手动在每个索引,它工作得很好!
每次我注释掉循环,程序就会以我想要的方式运行。所以我相信这是个循环。
源代码:
结构MapItem {
char type = 'E'; };
结构映射{
int size;
MapItem *items;};
int main () {
int selection;
int map_size;
Map new_map;
MapItem new_map_item;
enum MenuOptions {
INIT = -1,
NEW_GAME =1,
PRINT_MAP,
BUILD,
EXIT_PROGRAM
};
while (selection != EXIT_PROGRAM) {
cout << endl;
cout << NEW_GAME<< ". New Game" << endl;
cout << PRINT_MAP << ". Print Map" << endl;
cout << BUILD << ". Build Something" << endl;
cout << EXIT_PROGRAM << ". Exit" << endl;
//get selection , cin >> int , return int,
selection = get_selection();
switch (selection) {
case NEW_GAME:
//int map size (just extra variable i wanted to add)
//create_new_game () returns int , gets size for map.
// map is a one dimensional array of chars. map size will be a
// square (size*size)
map_size = create_new_game();
new_map.size = (map_size*map_size);
new_map.items = &new_map_item;
// test statements, code works if for loop is not there
cout << new_map.size;
cout << new_map.items[0].type;
//
// ! WHERE ERROR OCCURS !
//
for ( int index = 0; index <= (new_map.size); index++ ) {
new_map.items[index].type = new_map_item.type;
}
break;
**COMMAND LINE INPUT/OUTPUT:**
$ make
g++ -std=c++11 -c -Wall main.cpp
g++ -std=c++11 main.o -o driver
$ ./driver.exe
1. New Game
2. Print Map
3. Build Something
4. Exit
Enter your selection: 1
What size map would you like? 3
Segmentation fault (core dumped)发布于 2015-09-20 23:16:36
for ( int index = 0; index <= (new_map.size); index++ ) {
将在映射索引结束后运行0到n-1,您将使用0到n。
它应该是
for ( int index = 0; index < (new_map.size); index++ ) {
发布于 2015-09-20 23:21:52
我已经修正了运行时错误,这个错误是通过更改循环中的条件来修正的。
for ( int index = 0; index < map_size; index++ ) {
new_map.items[index].type = new_map_item.type;
cout << index;
}如果map_size是一个带有更新值的int,仍然不确定这有什么意义,但它是工作的。
https://stackoverflow.com/questions/32685266
复制相似问题