I'm trying to translate some pseudocode that starts indexing at -1. Will the following code work like I expect it to?
Code:int main() { int* a = new int[10]; a = &a[1]; a[-1] = 4; delete (a - 1); }
I'm trying to translate some pseudocode that starts indexing at -1. Will the following code work like I expect it to?
Code:int main() { int* a = new int[10]; a = &a[1]; a[-1] = 4; delete (a - 1); }
Assuming you don't use the same letter twice. (I.e., you could do int *b = &a[1] and go from there.)
(ETA: I should say, you might get warnings from your compiler (I think for example gcc warns on indices it can guarantee are always negative), but since your pointer, if used correctly, will always refer to valid memory everything is defined.)
More over, why would you want to do that? There might be data there that you don't want to mess with and could end up with errors or corruption.
"I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008
"the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010
If you are implementing a lookup table that maps values in the range [x, y], then you don't want to subtract x from each lookup -- it's more efficient to just adjust the base pointer such that the x'th element coincides with the zero'th element of the actual array.
Of course, merely possessing an out-of-bounds pointer is technically undefined, but not something I'd worry about in practice.
Code://try //{ if (a) do { f( b); } while(1); else do { f(!b); } while(1); //}