我对 C++ 中指针算术的行为感到困惑。我有一个数组,我想从当前数组向前移动 N 个元素。由于在 C++ 中指针是 BYTES 中的内存地址,所以对我来说代码应该是newaddr = curaddr + N * sizeof(mytype)
. 但是它产生了错误;后来我发现newaddr = curaddr + N
一切正常。为什么这样?它真的应该是地址+ N而不是地址+ N * sizeof吗?
我注意到它的部分代码(所有内存分配为一个块的二维数组):
// creating pointers to the beginning of each line
if((Content = (int **)malloc(_Height * sizeof(int *))) != NULL)
{
// allocating a single memory chunk for the whole array
if((Content[0] = (int *)malloc(_Width * _Height * sizeof(int))) != NULL)
{
// setting up line pointers' values
int * LineAddress = Content[0];
int Step = _Width * sizeof(int); // <-- this gives errors, just "_Width" is ok
for(int i=0; i<_Height; ++i)
{
Content[i] = LineAddress; // faster than
LineAddress += Step; // Content[i] = Content[0] + i * Step;
}
// everything went ok, setting Width and Height values now
Width = _Width;
Height = _Height;
// success
return 1;
}
else
{
// insufficient memory available
// need to delete line pointers
free(Content);
return 0;
}
}
else
{
// insufficient memory available
return 0;
}