c++ - Pointer to an array,why is this the address of the last element? -
i working tutorials point.com example.
int var[max] = {10, 100, 200}; int *ptr; // let have address of last element in pointer. ptr = &var[max-1]; (int = max; > 0; i--) { cout << "address of var[" << << "] = "; cout << ptr << endl; cout << "value of var[" << << "] = "; cout << *ptr << endl; // point previous location ptr--; } return 0; so, why &var[max - 1] , why not &var[max]? if not use reference, possible solve problem in different manner?
because arrays in c++ zero-based, i.e. start 0 , end @ n-1. var[max] element past end of array, out-of-bounds , accessing undefined behaviour.
var { 10, 100, 200 } index ^0 ^1^ ^2^ ^3?
Comments
Post a Comment