c++ - Internal logic of operator [] when dealing with pointers -
i've been studying c++ couple of months , decided more logic of pointers , arrays. i've been taught in uni pretty basic - pointers contain address of variable. when array created, pointer first element created.
so started experimenting bit. (and got conclusion need confirmation for). first of created
int arr[10]; int* ptr = &arr[5]; and imagine
cout << ptr[3]; gave me 8th element of array. next tried
int num = 6; int* ptr2 = # cout << ptr2[5]; cout << ptr2 + 5; which great delight (not irony) returned same addresses. though num wasn't array.
the conclusion got: array not special in c++. it's pointer first element (already typed that). more important: can think every pointer in manner of object of class variable*. operator [] overloaded in class int*? example along lines of:
int operator[] (int index){ return *(arrayfirstaddress + index); } what interesting me in these experiments operator [] works every pointer. (so it's overloading operator instances of said class)
of course, can wrong possible. couldn't find information in web, since didn't know how word question decided ask here. extremely helpful if explained me if i'm right/wrong/very wrong , why.
you find definition of subscripting, i.e. expression ptr2[5] in c++ standard, e.g. in this online c++ draft standard:
5.2.1 subscripting [expr.sub]
(1) ... expression e1[e2] identical (by definition) *((e1)+(e2))
so "discovery" sounds correct, although examples seem have bugs (e.g. ptr2[5] should not return address int value, whereas ptr2+5 address not int value; suppose meant &ptr2[5]).
further, code not prove of discovery based on undefined behaviour. may yield supports "discovery", discovery still not valid, , opposite (really!).
the reason why undefined behaviour pointer arithmetics ptr2+5 undefined behaviour if result out of range of allocated memory block ptr2 points (which case in example):
5.7 additive operators
(6) ... unless both pointers point elements of same array object, or 1 past last element of array object, behavior undefined.
different compilers, different optimization settings, , slight modifications anywhere in program may let compiler other things here.
Comments
Post a Comment