Trayvon Banks Ответов: 2

Преобразования смещения обозначения для арифметических операций над указателями.


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


Что я уже пробовал:

Поиск в Google правильной документации указателей
Подумывал начать все сначала.

2 Ответов

Рейтинг:
0

Richard MacCutchan

*(*(boardArr + i )+ j) == pos;//parsing string into bArr

//neighbor check nested for organism
pos  = *(*(boardArr + i)+ j);//position of index within

Один из худших способов обращения к памяти на любом языке; просто не делайте этого. И первое утверждение ничего не делает, но если вы намеревались написать один = знак, первый раз в жизни pos не имеет никакой ценности, так что это вызовет проблемы.

Начните с установки указателей на каждую часть массива например
pos = *boardArr;  // point to the first element of boaradArr

Я не уверен, что остальная часть кода должна делать, поэтому трудно добавить больше. Достаточно сказать, что вы можете создавать другие указатели в виде положительных или отрицательных смещений от pos.


Рейтинг:
0

KarstenK

Этот код должен делать свою работу.

char** pointer = boardArr;//set initial running 
for(int i = 0; i < rows; i++) //rows
{
    getline(inFile, line);

    for(int j = 0; j < cols; j++) //cols
    {
        *pointer = pos;//parsing string into bArr
        pointer++;//move pointer one memory block size
    }
    pointer++;//move pointer one memory block size
Пожалуйста, проверьте, что оператор ++ выполняет правильную работу.

Примечание: когда вы работаете с одним столбцом, начинается следующее смещение после колонка. Так
int offset = (i * row) + j;//imagine a chess board
PS: мой опыт говорит о том, что тщательная проверка границ-это основа арифметики указателей. Это общий источник проблем :-O