1

I am kinda new to programming, so pardon me for any stupid questions :P, i noticed that when i write this

int main()
    {
        string s;
        s[0]='a';
        cout<<s.size();
        cout<<s<<" ";
        cout<<s[0];
       return 0;
    }

The output is 0 a , firstly why is the size 0? and why didn't anything get printed when i write cout<<s; but it gives a for cout<<s[0]. if i use push_back it gives normal out put.

int main()
{
    string s;
    s.push_back('a');
    cout<<s.size();
    cout<<s<<" ";
    cout<<s[0];
   return 0;
}

output :- 1a a

I might have overlooked something but i would be really appreciate if some could point out the cause. Thank you.

EDIT: Such fast replies! thanks for your answers, i couldn't figues out how to reply to comments so edited the question body(first time using stackoverflow), (any help on this would be appreciated as well), one more thing so when i use cout<<s[0] does it give a because a was stored on the next address of string s? and once again thanks for clearing that up!

1
  • 5
    s[0]='a'; invokes undefined behavior Commented Dec 31, 2018 at 17:02

5 Answers 5

5

What you've overlooked is that in C++ strings don't automatically grow when you assign characters to them. So

string s;
s[0]='a';

is an error because the s has size zero so there is no 'room' for the character 'a'. The correct way to add a character to a string is to use push_back which is why your second example works.

Because of the error your first example has what's called undefined behaviour (UB for short). This means the output of your program is not predictable at all, and it's more or less a waste of time asking why it outputs what it does. It could just as easily crash.

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

3 Comments

so it could give any value when i use cout<<s[0]? or even crash? and does it give a because a was stored on the next memory location after s or in this case as s is empty, a was stored on the same location as s?
@bufftowel Undefined behavior is undefined. Code that invokes undefined behavior, could even appear to be working fine, until you decide to demo your code to the client, at which point it could invoke nasal demons (make demons fly out of your nose).
@bufftowel Yes undefined means undefined. Of course if you know something about how your compiler works you could predict what the outcome will be. But the point is that there's no particular behaviour specified by the C++ language.
4

This:

   string s;

creates a string containing no characters. Then this:

  s[0]='a';

attempts to make a change to one of those non-existent characters. The result of this is undefined behaviour - your program goes into an unknown state.

If you would like to make your compiler warn you about this problem, you can use the at() member function of string:

  s.at(0) = 'a';

Now your program will throw an std::out_of_range exception when you try to change that non-existant character.

Comments

0

Containers don't automatically allocate storage, so you are writing outside the allocated storage. In other words, that's a bug in your program. One advise: Many C++ implementations have a way to activate diagnostics for debugging programs, those would have caught this error.

Comments

0

when I write this

string s;
s[0]='a';

the output is 0, firstly why is the size 0?

The output is zero because operator[i] assumes that the string has sufficient space to store i+1 characters. In your case, string's size is zero, so accessing element at index 0 is undefined behavior.

and why didn't anything get printed when I write to cout

The same thing reason applies: after undefined behavior the program could output anything, but it happens to output nothing.

Comments

-1
int main()
{
    string s;
    s='a';
    cout<<s.size();
    cout<<s<<" ";
    cout<<s[0];
    return 0;
} 

Just take off [0] after s in initialisation because s is of type string not type char.

Just write s and it will work.

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.