Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When is it ever useful to use negative indexing of a C array?

C arrays allow for negative indexing, but I can’t think of a use for that, seeing that you’ll never have an element at a negative index.

Sure, you can do this:

struct Foo {
   int arr1[3] = { 1, 2, 3 };
   int arr2[3] = { 4, 5, 6 };
};

int main() {
   Foo foo;
   std::cout << foo.arr2[-2] << std::endl; //output is 2
}

But why would you ever want to do something like that? In any case, when is negative indexing of an array necessary, and in what domains would you be doing it in?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Remember that when you index an array, you get the element at index N which is the element at &array[0] + sizeof(array[0]) * N.

Suppose you have this code:

#include <stdio.h>
int main()
{ 
    int a[5] = {5, 2, 7, 4, 3};
    int* b = &a[2];
    printf("%d", b[-1]); // prints 2
   
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading