преобразование нотации смещения в арифметику указателей в 2d массивах c ++ - PullRequest
0 голосов
/ 09 октября 2018

Итак, я пытаюсь выполнить назначение, используя массивы двухмерных указателей.Я проходил этот процесс, когда понял, что одним из требований было то, что я должен был использовать арифметику указателей, но вместо этого я использовал нотацию смещения.Итак, мой вопрос к вам, ребята, каков наилучший метод преобразования моей записи смещения в арифметику указателей без полного переписывания программы ???Кроме того, при прохождении через мой 2d массив, какие параметры я вызываю для моей функции 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;
}

1 Ответ

0 голосов
/ 09 октября 2018

Нет причин использовать арифметику указателей для таких простых операций.

Просто используйте 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 &row.Они малы, и компилятор может упаковать их только в один регистр процессора.

...