0

While doing some code,I am not having the expected results due to self change in array values inside and outside the loop.why its happening?

char* arr[2];
int i=0;
char inp[20];
while(i<2)
    {
    cin>>inp;
    arr[i]=inp;
    cout<<arr[i]<<endl;
    i++;
    }
cout<<arr[0]<<endl;
cout<<arr[1]<<endl;

For the input :

aaa
bbb

The output is:

aaa
bbb
bbb
bbb
4
  • are you sure about your output? Ideone produces a different one, consistent with the already given answers: ideone.com/y2YQjX Commented Jan 25, 2016 at 12:19
  • @iharob Arrays - especially the encapsulated std::array - are very valid in many cases. Sure, for ad-hoc dynamic arrays like this seems to be, vector is better, but on a general level - as you've phrased it - I don't agree with either of the blanket recommendations you're making. Commented Jan 25, 2016 at 12:32
  • @M.M Thank you for the clarification, I will delete the comment. Commented Jan 25, 2016 at 12:44
  • By mistake i had written wrong output in the last two rows..i have corrected it as bbb instead of aaa ...So sorry for my mistake @Anedar Commented Jan 25, 2016 at 14:46

1 Answer 1

3

The following line doesn't do what you think:

    arr[i]=inp;

Here you are assigning to arr[i] a pointer to inp, not copying the input buffer into arr[i]. During the same iteration (i.e. at the first cout << arr[i]) everything is fine. As soon as you overwrite the contents of inp, the changes will reflect in all the cells of arr you have assigned to that same pointer. In fact, at the end of the loop all cells of arr point to inp, which means you will always see the last value extracted from cin.

As a solution, make arr an array of "strings" and copy the input buffer using strncpy:

char arr[2][20];
int i=0;
char inp[20];
while(i<2)
    {
    cin>>inp;
    strncpy(arr[i], inp, 20);
    cout<<arr[i]<<endl;
    i++;
    }
cout<<arr[0]<<endl;
cout<<arr[1]<<endl;

Or use C++ std::string if possible.

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

5 Comments

Still curious why the two last lines are aaa, not bbb as expected. Probably a bad manip from OP.
@mikedu95 my best guess is that OP made a mistake in writing the output by hand instead of copy&pasting it from the output of the program. In any case, the issue here is pretty clear :)
Yess...It was a mistake...I was just confused that why I was getting bbb all the time... Thanx @StefanoSanfilippo
Also ..please can you suggest way to store the values that I want instead of modifying them like in this case?
@Himanshu I am not sure I understood correctly your question.

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.