0

I came across with a statement with function call and as well as array index in the kind of code mentioned below .In this the statement s=o.init()[-1] is returning value of a1[0]. I am not cleared with the concept of how it is working, what this statement o.init()[-1] will do ?, i know 0.init() will give a call to function but what does [-1] specify? Pls help to solve this query?

#include<iostream>
using namespace std;

class a
{
  char a1[1000];

  public:
  a()
 {
    a1[0]='a';
 }
  char* init()
  {
     cout<<"value of a1 is"<<a1<<endl;
     return a1+1;
  }
};

int main()
{
   a o;
  char s;
  s=o.init()[-1];


cout<<"value of s  is"<<s<<endl;
}

3 Answers 3

2

init() returns a pointer to a1[1]. o.init()[-1]; subtracts 1 from that pointer (so, you get a pointer to a1[0]) and dereferences it and you get a1[0].

Sign up to request clarification or add additional context in comments.

Comments

1

The return value of the method is char*. So the index operator subtracts one from the address, and dereferences it.

Comments

1

init returns a char* so init()[-1] will just take the pointer one char backwards in the memory.

Imagine it like:

char* arr = o.init();

and then:

arr--;

As you can see, your function returns the array+1, so in order to take 'a', or rather the first value, you'll have to go one step backwards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.