A aritmética de ponteiro em C ++ usa o incremento de tamanho (tipo) em vez do incremento de byte?
Estou confuso com o comportamento da aritmética de ponteiros em C ++. Eu tenho uma matriz e quero ir N elementos para a frente a partir do atual. Como em C ++ o ponteiro é endereço de memória em BYTES, pareceu-me lógico que o código fossenewaddr = curaddr + N * sizeof(mytype)
. Produziu erros embora; mais tarde eu achei que comnewaddr = curaddr + N
tudo funciona corretamente. Por quê? Deveria ser realmente endereço + N em vez de endereço + N * sizeof?
Parte do meu código onde eu notei (matriz 2D com toda a memória alocada como um pedaço):
// 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;
}