【问题标题】:Segmentation fault (core dumped) ! structs, arrays分段错误(核心转储)!结构体、数组
【发布时间】: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)

【问题讨论】:

    标签: arrays struct


    【解决方案1】:

    for ( int index = 0; index &lt;= (new_map.size); index++ ) {

    会让你跑过地图的尽头 - 索引运行 0 到 n-1,你正在使用 0 到 n。

    应该是

    for ( int index = 0; index &lt; (new_map.size); index++ ) {

    【讨论】:

    • 我实际上只是想出了这一点,以及如何停止运行时错误,当我使用 (index
    【解决方案2】:

    我已经修复了运行时错误,该错误是通过更改循环中的条件来修复的

    for ( int index = 0; index < map_size; index++ ) {
                    new_map.items[index].type = new_map_item.type;
                    cout << index;
    }
    

    其中 map_size 是具有更新值的 int,仍然不确定这是否有意义,但它可以工作。

    【讨论】:

    • 这正是我在回答中所说的 - 你将 0 到 size-1(正确)而不是原来的 0 到 size(一个太多)。你原来有&lt;=,而你应该有&lt;)
    • 不完全是,我尝试切换运算符,但在我将比较的右侧切换为 int 之前它仍然不起作用。
    猜你喜欢
    • 2017-06-12
    • 2018-01-05
    • 2020-04-18
    • 1970-01-01
    • 2015-06-25
    • 2021-06-03
    相关资源
    最近更新 更多