我對C++中指針算術的行爲感到困惑。我有一個數組,我想從當前的元素前進N個元素。由於在C++中指針是BYTES中的內存地址,因此代碼爲newaddr = curaddr + N * sizeof(mytype)
對我來說似乎合乎邏輯。它雖然產生了錯誤;後來我發現newaddr = curaddr + N
一切正常。爲什麼這樣?如果它真的是地址+ N而不是地址+ N * sizeof?我的代碼C++中的指針運算使用sizeof(type)增量而不是字節增量?
部分,其中我注意到它(2D陣列分配爲一個塊的所有存儲器):
// 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 - 不,「number + 1」是*不一定是「下一個字節」。只有當「數字」恰好是「char」(或「unsigned char」)時纔會如此。 – paulsm4