首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >分割故障(核心倾弃)!结构,数组

分割故障(核心倾弃)!结构,数组
EN

Stack Overflow用户
提问于 2015-09-20 23:10:48
回答 2查看 172关注 0票数 2

在我的“for循环”中得到一个错误。

程序编译并执行,

但是当我尝试使用case NEW_GAME的代码时:在我的开关语句中,程序‘挂起’然后输出‘分段错误(内核转储)’,我认为这意味着程序试图访问一些内存块,但我不明白为什么会发生这种情况……

我尝试了填充,new_map.itemsindex.type手动在每个索引,它工作得很好!

每次我注释掉循环,程序就会以我想要的方式运行。所以我相信这是个循环。

源代码:

结构MapItem {

代码语言:javascript
复制
char type = 'E';    

};

结构映射{

代码语言:javascript
复制
int size;
MapItem *items;

};

int main () {

代码语言:javascript
复制
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;

代码语言:javascript
复制
    **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)
EN

回答 2

Stack Overflow用户

发布于 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++ ) {

票数 1
EN

Stack Overflow用户

发布于 2015-09-20 23:21:52

我已经修正了运行时错误,这个错误是通过更改循环中的条件来修正的。

代码语言:javascript
复制
for ( int index = 0; index < map_size; index++ ) {
                new_map.items[index].type = new_map_item.type;
                cout << index;
}

如果map_size是一个带有更新值的int,仍然不确定这有什么意义,但它是工作的。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32685266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档