c++vectorperiodicity

How to printing all 8 neighbors in a 2D vector (Segmentation Fault)


I am attempting to access ALL 8 neighbors of an index on a 2D vector.

I then try to do the following pseudocode to find all 8 neighbors

cout << grid[columnindex-(-1->1)][rowIndex-(-1->1)] << endl;

However, when I do this I get a segmentation fault. I am unsure why.


Solution

  • I get a segmentation fault.

    Code is indexing outside array bounds with negative indices.
    Index calculation needs to wrap around. Use modulo arithmetic.

    // cout << grid[c-incc][r-incr] << endl;
    int ci = (c-incc + vecSize)%vecSize;
    int ri = (r-incr + veciSize)%veciSize;
    cout << grid[ci][ri] << endl;
    

    Code uses (c-incc + vecSize)%vecSize; rather than (c-incc)%vecSize; to deal with c-incc < 0 as % is not the modulo operator, but a remainder operator.