1

I have been playing with pointers, to understand how to use then, I tried:

baz + sizeof(char)

and the code is working correctly, I get the right value, I don't understand why.

I was expecting to work correctly with:

baz + sizeof(Rectangle)

but I get a random number when I use it. how is baz[1:0] array organized? Shouldn't it be an array of 'Rectangle' objects?

#include <iostream>
using namespace std;

class Rectangle
{
        int width, height;
public:
    Rectangle (int x, int y): width(x), height(y) {}
    int area ()
    {
        return width * height;
    }
};

int main(int argc, const char * argv[]) 
{
    Rectangle obj (10,4);
    Rectangle *foo, *bar, *baz;
    foo = &obj;
    bar = new Rectangle (5,6);
    baz = new Rectangle[2] { {2,5}, {1,2}} ;
    cout << "obj    area: " << obj.area() << endl;
    cout << "foo    area: " <<    foo -> area() << endl;
    cout << "bar    area: " <<    (*bar).area() << endl;
    cout << "bar    area: " <<    bar -> area() << endl;
    cout << "baz[0] area: " <<    baz[0].area() << endl;
    cout << "baz[1] area: " <<    (baz + sizeof(char)) -> area() << endl;

}
Max Bonino
  • 33
  • 4
  • 2
    `baz + sizeof(char)` is `baz + 1` - the compiler sees that the type of `baz` is `Rectangle*` so it knows how much it needs to add to get to the next element in an array of `Rectangle` – UnholySheep Aug 16 '20 at 19:03
  • 3
    `baz + x` offsets by `x` elements (of type `Rectangle` in this case), not by `x` bytes. `sizeof(char) == 1` by definition, so `baz + sizeof(char)` refers to `baz[1]`, a valid object. `baz + sizeof(Rectangle)` refers to something like `baz[8]`, well out of bounds. – Igor Tandetnik Aug 16 '20 at 19:03
  • 1
    In both C and C++, adding or subtracting some value from a pointer automatically multiplies the pointer's memory address by `sizeof` of what it points to, and `sizeof(char)` just happens to be 1, so it works correctly in this case. See the linked question for more information. – Sam Varshavchik Aug 16 '20 at 19:13

0 Answers0