0

I just encountered an input statement for char array in c++ and I didn't understand how it works.

char s[100];
cin >> s + 1;
cout << s + 1;

Input : Harold

Output: Harold

Can anyone explain to me how it works?

6
  • 2
    It works exactly like any other char array. Sorry we don't know how much of C++ you know, so it's a bit difficult to pick a starting point for an explanation. Why exactly are you confused about these lines? Commented Dec 28, 2018 at 18:58
  • If it said ((&s[0]) + 1) would you understand it? Commented Dec 28, 2018 at 21:55
  • Make these changes char s[100] = "a"; Now at the end add cout << '\n' << s << '\n'; With that, can you tell what is going on? Commented Dec 28, 2018 at 22:02
  • @n.m. I was wondering how it works. We used to use loops to input an array but didn't know about this. Now I get this. Thanks a lot Commented Dec 30, 2018 at 6:40
  • @DavidSchwartz Yeah i got this. Thanks a lot. Commented Dec 30, 2018 at 6:44

1 Answer 1

1

When you give the input 'Harold', the indices from 1 to 6 (As you do with s+1) will be assigned with the given characters. Other indices still contain garbages. This array looks like this: {'X','H','a','r','o','l','d','X','X',........} (Here 'X' means garbage)

But the thing is that when you want to get this array as output from s+1 (literally s[1]), It shows only the value you have assigned. Hence the output 'Harold'.

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

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.