【发布时间】:2015-09-20 23:10:48
【问题描述】:
在我的“for 循环”中出错。
程序编译并执行,
但是当我尝试使用案例 NEW_GAME 中的代码时:在我的 switch 语句中,程序“挂起”然后输出 'Segmentation fault (core dumped)' 我认为这意味着程序正在尝试访问一些内存,但我不明白为什么会这样......
...因为我尝试填充,new_map.items[index].type 在每个索引处手动填充,效果很好!
每次我注释掉循环时,程序都会按照我想要的方式运行。所以我相信它是循环。
源代码:
结构地图项 {
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)
【问题讨论】: