2

次のコードでセグメンテーション違反が発生するのはなぜですか?

    struct Cell
    {
        cellMode mode;
        bool visited;
        //bool scanned;
        int rowIndex;
        int colIndex;
        Cell *neighbours;//if using Cell neighbours[3] i am getting a compilation error

        Cell()
        {
            neighbours = new Cell[3];//seg fault here
        }
    };

静的配列を使用すると、次のエラーが発生します

neighbours has incomplete type

4

3 に答える 3

6

If you new 3 Cells in Cell's constructor you are calling 3 more Cell's constructors. Each of those 3 then calls 3 more, and so on. Until, a... wait for it... stack overflow. Hurrah. It's infinite.

于 2013-06-17T21:02:00.637 に答える
5

You wrote an infinitely recursive function. Your Cell::Cell constructor indirectly calls itself thorough new expression, which in turn calls Cell::Cell again, again and again... This eventually leads to stack overflow and crash.

(Also, it is not possible to have an explicit array of Cell objects inside a Cell object. Such a data structure would be infinitely nested, i.e. it would have infinite size.)

Note that there's nothing generally wrong with recursion per se. But it has to end at some point. If you want to build your tree recursively, you can do so, but you have to make sure your recursion bottoms-out at one point or another. I.e. your tree has to have leaf nodes. What you have now is a tree without leaf nodes. It is an infinite recursion that attempts to build an infinitely large tree. This is not possible. It makes no sense.

When it is time to build your leaf nodes - only you can answer. We don't know what kind of tree your are trying to build.

于 2013-06-17T21:02:07.253 に答える
0

コンストラクターはインスタンスごとに 3 回自分自身を呼び出しているため、基本的に、終わりのない再帰による無限ループを作成しています。それがあなたの問題です。

于 2013-06-17T21:03:12.480 に答える