0

I am familiar with python's indexing system but not with C++'s... so please help me

I want to index an array negatively...

I have tried

int myarray[5] = {1,2,3,4,5};
cout << myarray[-1];

but it is generating some number very big which is not a part of this array...

Prakhar Parikh
  • 177
  • 2
  • 13
  • `myarray[-1]` is accessing the element *one before* the first element in the array. Which is undefined behavior. In practice, you're just getting uninitialized stack garbage. – Cody Gray - on strike Jun 27 '21 at 09:55
  • You can compute the size of array using `sizeof` and then use `arr_size - 1` to access the last element: `int arr_size = sizeof(myarray) / sizeof(int); cout << myarray[arr_size - 1];` – kiner_shah Jun 27 '21 at 09:57
  • @kiner_shah Note that (1) the result of the `sizeof` operator is `std::size_t`, not `int`, (2) the correct way to write that in standard C++ is simply `std::size`, and (3) your trick is very dangerous because it will stop working as soon as that array decays to a pointer. I've seen that bite *many* programmers, especially those who are new to C or C++. – Cody Gray - on strike Jun 27 '21 at 09:58
  • @CodyGray, Yeah I forgot, `sizeof` returns `size_t`. Nice catch :-) And yeah, `sizeof` can be a problem if they start using pointers. Is `std::size` supported since C++11? – kiner_shah Jun 27 '21 at 10:01
  • 1
    Nah, `std::size` is C++17 and later. The catch is not that you "start using pointers", but rather that C-style arrays decay *implicitly* to pointers, which means that you end up using pointers even when you don't mean to do so! Especially as a beginner. @kiner_shah – Cody Gray - on strike Jun 27 '21 at 10:03
  • C++ does not have Python-like negative indexing. – Eljay Jun 27 '21 at 12:50

1 Answers1

1

You might want to consider using std::vector, which gives you access to .size(), so to get the last element you can do .size()-1 (assuming nonempty).

For a more advanced, but conceptually tidier solution, you might want to look at iterator based solutions, like .end() or .rend().

std::vector<int> myArray = { 1,2,3,4,5};
std::cout << myArray[myArray.size()-1] << std::endl;
  • This is good advice, but if you're going to answer the question, you need to start out by posting the actual answer: why is the observed behavior seen? – Cody Gray - on strike Jun 27 '21 at 09:55
  • Thats already been answered in a comment. Feel free to edit? – SomeGues23ke Jun 27 '21 at 09:56
  • On an unrelated note, `std::endl` is a bad habit. That forces a flush of the stream, which is almost never want you want. When you want a line break, just do `<< '\n'`. – Cody Gray - on strike Jun 27 '21 at 09:57
  • sorry bro... i am new to C++, using vs code... your answer didn't work for me... if possible send me the full code by editing your answer.... from first line to the last... thank you – Prakhar Parikh Jun 28 '21 at 08:25