【问题标题】:converting offset notation to pointer arithmetic in 2d arrays c++将偏移符号转换为二维数组中的指针算术 c++
【发布时间】:2019-03-14 10:20:22
【问题描述】:

所以我正在尝试使用二维指针数组完成分配。当我意识到要求之一是我应该使用指针算术时,我正在经历这个过程,但我一直在使用偏移表示法。所以我对你们的问题是在不完全重写程序的情况下将我的偏移符号转换为指针算术的最佳方法是什么?此外,当穿越我的二维数组时,我需要为我的 outofbounds 函数调用哪些参数才能使其正常工作?任何建议将不胜感激,并提前感谢您。

    //move through string by parsing  to insert each char into array element position

void rules(char** boardArr,int  &rows, fstream inFile, string &line, int &cols)
{
    char* pos;
    char ncount;
    for(int i = 0; i < rows; i++) //rows
    {
        getline(inFile, line);

        for(int j = 0; j < cols; j++) //cols
        {
            *(*(boardArr + i )+ j) == pos;//parsing string into bArr

            //neighbor check nested for organism
            pos  = *(*(boardArr + i)+ j);//position of index within
            if(*(*(boardArr + i+1)+ j)=='*')//checking pos to the right of pos index
            {
                //outofbounds()
                ncount++;
            }
            if(*(*(boardArr + i-1)+ j)=='*')//checking pos to the left of pos index
            {
                //outofbounds()
                ncount++;
            }
            if(*(*(boardArr + i)+ j+1)=='*')//checking pos to the above of pos index
            {
                //outofbounds()
                ncount++;
            }
            if(*(*(boardArr + i+1)+ j+1)=='*')//checking pos to the above and to the right of pos index
            {
                //outofbounds()
                ncount++;
            }
            if(*(*(boardArr + i-1)+ j+1)=='*')//checking pos above and to the  left of pos index
            {
                //outofbounds()
                ncount++;
            }
            if(*(*(boardArr + i-1)+ j-1)=='*')//checking pos below and to the left of pos index
            {
                //outofbounds()
                ncount++;
            }
            if(*(*(boardArr + i-1)+ j)=='*')//checking pos below of pos index
            {
                //outofbounds()
                ncount++;
            }
            if(*(*(boardArr + i-1)+ j+1)=='*')//checking pos below and to the right of pos index
            {
                //outofbounds()
                ncount++;
            }
            //row[i, row[i]-1])
            //cout<<*(*(boardArr + i)+ j);//assigning position to check for neighbors

        }



    }

//how to move through 2d array pointer arithmetic style

//boardArr[rows][cols] == *(*(boardArr + rows)+ cols)

//keep relationship between the numbers
//*(())
//If a cell contains an organism and has fewer than 2 neighbors, the organism dies of loneliness.
//A neighbor is an organism in one of the 8 spots (or fewer if on the edge) around a cell
//If a cell contains an organism and has more than 3 neighbors, it dies from overcrowding.
// If an empty location has exactly three neighbors, an organism is born in that location.
//returns nothing
}
bool  outofbounds( int &rows, int &cols, int i, int j)
{
    if((i >0 && i< rows)  && (j < cols && j > 0))
    {
        return true;
    }
    else
        return false;
}

【问题讨论】:

  • i == 0 时,*(boardArr + i-1) 会发生什么?或者当i == rows - 1 而你有*(boardArr + i+1)?当然,j 也一样。
  • 当 i ==0 时,*(boardArr + i -1) 应该移动到左/前索引地址并检查它是否有 *。在检查时,我通过我的 outofbounds 函数(应该将其保留为 inbounds)以查看它是否应该在移动到索引中的下一个位置之前使用该信息
  • 为什么不使用boardArr[i][j] 而不是*(*(boardArr + i)+ j)
  • 如果i == 0*(boardArr + i - 1) 将是*(boardArr + 0 - 1)*(boardArr - 1) 等于boardArr[-1]。这超出了界限,在 C++ 中,索引越界导致undefined behavior。索引数组或内存时,您应该永远越界。如果i == rows - 1 thne 你用*(boardArr + i + 1)other 方向上越界。

标签: c++ arrays pointers multidimensional-array pointer-arithmetic


【解决方案1】:

没有理由对这种简单的操作使用指针算法。

只需使用arr[i][j] 来读取/写入数据。

您还应该在对内存进行任何读/写操作之前检查边界。这很危险,可能会使您的程序崩溃。

这是我如何实现这些东西的版本。

#include <iostream>


/* it is good practice to move functions with special context to classes */
class SafeCharMatrix
{

private:

    /* your board */
    /* `char const* const*` provides that nobody can change data */
    char const* const* _ptr;
    int _rows;
    int _cols;

public:

    SafeCharMatrix(char const* const* ptr, int rows, int cols) :
        _ptr(ptr), _rows(rows), _cols(cols)
    {}

    /* valid check bounds algorithm */
    bool CheckBounds(int x, int y) const
    {
        if (x < 0 || x >= _cols)
            return false;

        if (y < 0 || y >= _rows)
            return false;

        return true;
    }

    bool CheckCharSafe(int x, int y, char c) const
    {
        /* check bounds before read/write acces to memory */
        if (!CheckBounds(x, y))
            return false;

        return _ptr[x][y] == c;
    }

    int CountNeighborsSafe(int x, int y, char c) const
    {
        int count = 0;

        count += CheckCharSafe(x - 1, y - 1, c) ? 1 : 0;
        count += CheckCharSafe(x - 1, y    , c) ? 1 : 0;
        count += CheckCharSafe(x - 1, y + 1, c) ? 1 : 0;
        count += CheckCharSafe(x    , y - 1, c) ? 1 : 0;
        /* ignore center (x, y) */
        count += CheckCharSafe(x    , y + 1, c) ? 1 : 0;
        count += CheckCharSafe(x + 1, y - 1, c) ? 1 : 0;
        count += CheckCharSafe(x + 1, y    , c) ? 1 : 0;
        count += CheckCharSafe(x + 1, y + 1, c) ? 1 : 0;

        return count;
    }

};


/* fill you board before this */
void rules(char const* const* boardArr, int rows, int cols)
{
    SafeCharMatrix matrix(boardArr, rows, cols);

    for (int i = 0; i < rows; ++i) /* y axis */
    {
        for (int j = 0; j < cols; ++j) /* x axis */
        {
            int countOfNeighbors = matrix.CountNeighborsSafe(j, i, '*');

            /* do whatever you want */

            std::cout
                << "x: " << j << ", "
                << "y: " << i << ", "
                << "count: " << countOfNeighbors << "\n";
        }
    }
}


/* just example of how it can works */
int main()
{
    char r1[3] = {  0 ,  0 , '*'};
    char r2[3] = {  0 ,  0 ,  0 };
    char r3[3] = { '*',  0 ,  0 };

    char* m[3];
    m[0] = r1;
    m[1] = r2;
    m[2] = r3;

    rules(m, 3, 3);
}

编辑:

不要通过引用传递像 int 数字这样的简单参数:int &amp;row。它们很小,编译器可以将它们打包在一个处理器寄存器中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多