Jake2k13
Jake2k13

Reputation: 231

Runtime Error Using Char Array to Display a String in VC2010

I am "running" this code:

#include <iostream>

int main()
{

    char name[5] = {'J', 'a', 'k', 'e', '\0'};

    std::cout << name[5];

    std::cin.get();
    std::cin.get();

    return 0;
}

referring to my C++ Primer, this code is correct. The Run-Time error I am receiving is this (copy and pasted directly from the dialog):

"Run-Time Check Failure #3 - The variable 'name' is being used without being initialized."

I do understand this error, but I don't see how I can fix it. I did Initialize the variable. I want to know how I can solve this, or if I did make a mistake, how I could fix it. Thanks.

Upvotes: 0

Views: 104

Answers (1)

ScarletAmaranth
ScarletAmaranth

Reputation: 5101

Name is 5 element array, therefore, the last element is name[4].

You're trying to print the "sixth" element, which doesn't exist with: std::cout << name[5];

If you'd like to print the entire thing, then std::cout<<name; would work well as you correctly null terminated your array.

If you want to print the fifth element ('\0'), then std::cout<<name[4].

Upvotes: 2

Related Questions