简体   繁体   English

使用Char数组在VC2010中显示字符串的运行时错误

[英]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. 参考我的C ++ Primer,这段代码是正确的。 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." “运行时检查失败#3 - 正在使用变量'name'而未进行初始化。”

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. 谢谢。

Name is 5 element array, therefore, the last element is name[4] . Name是5个元素数组,因此,最后一个元素是name[4]

You're trying to print the "sixth" element, which doesn't exist with: std::cout << name[5]; 你试图打印“第六”元素,它不存在: std::cout << name[5];

If you'd like to print the entire thing, then std::cout<<name; 如果你想打印整个东西,那么std::cout<<name; would work well as you correctly null terminated your array. 你正确地null终止你的数组会很好。

If you want to print the fifth element ('\\0'), then std::cout<<name[4] . 如果要打印第五个元素('\\ 0'),那么std::cout<<name[4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM