【发布时间】:2012-06-14 16:34:18
【问题描述】:
我对 C++ 中指针运算的行为感到困惑。我有一个数组,我想从当前数组向前移动 N 个元素。由于在 C++ 中指针是 BYTES 中的内存地址,因此对我来说代码是 newaddr = curaddr + N * sizeof(mytype) 似乎是合乎逻辑的。但是它产生了错误;后来我发现newaddr = curaddr + N 一切正常。为什么这样?真的应该是address + N而不是address + 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;
}
【问题讨论】:
-
你检查过语言规范吗?
-
在那里发现指针有一个内存地址作为字节偏移量(即内存中的第N个字节)。这就是为什么它看起来像一个数字 + 1 = 下一个字节。
-
@fynjyzn - 不,“数字 + 1”不一定是“下一个字节”。仅当“数字”恰好是“字符”(或“无符号字符”)时才会为真。
标签: memory-management pointer-arithmetic