【发布时间】: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 - 1thne 你用*(boardArr + i + 1)在other 方向上越界。
标签: c++ arrays pointers multidimensional-array pointer-arithmetic