I have a data type called 'tod', with which I create arrays. To iterate between elements of this type inside function (with pointer), I want to use an offset. However, this offset gets squared during operation:
tod theTime[] = { {12,0,0, "noon"}, {0,0,0, "midnight"}, {11,30,0, "lunch time"}, {18,45,0, "supper time"}, {23,59,59, "bed time"} };
auto tsize = sizeof(tod);
auto p1 = &theTime[0];
auto p2 = &theTime[0] + tsize;
cout << "size of tod = " << tsize << endl;
cout << "p1 = " << p1 << endl;
cout << "p2 = " << p2 << endl;
That gives me:
size of tod = 44
p1 = 0x7ffd3e3b0bf0
p2 = 0x7ffd3e3b1380
The difference between the two hex values comes down to 0x790, which is 1936 (decimal) and 44^2. How is this happening? Someone please help.
You're misunderstanding about pointer arithmetic:
If the pointer P points to the ith element of an array, then the expressions P+n, n+P, and P-n are pointers of the same type that point to the i+nth, i+nth, and i-nth element of the same array, respectively.
e.g. &theTime[0] + 1
will return the pointer pointing to the 2nd element of the array theTime
; then &theTime[0] + tsize
will try to return the pointer pointing to the tsize + 1
th element (note it's getting out of the bound and leads to UB). That's why you got 1936
, i.e. 44 * 44
.