¿La aritmética de punteros en C ++ utiliza el incremento de tamaño de (tipo) en lugar del incremento de bytes?
Estoy confundido por el comportamiento de la aritmética de punteros en C ++. Tengo una matriz y quiero adelantar N elementos desde la actual. Ya que en C ++ el puntero es la dirección de memoria en BYTES, me pareció lógico que el código fueranewaddr = curaddr + N * sizeof(mytype)
. Aunque produjo errores; más tarde encontré que connewaddr = curaddr + N
todo funciona correctamente ¿Porque? ¿Debería ser realmente la dirección + N en lugar de la dirección + N * sizeof?
Parte de mi código donde lo noté (matriz 2D con toda la memoria asignada como una porción):
// 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;
}