c++ - 数组初始化

标签 c++ visual-c++

我有两种类型的数组初始化将用于字符串构造函数

int main() {
    //char foo [] = { 'a', 'd' }; 
    char foo[] = "ad";

    std::string s = foo;

    cout<<s;

    int i;
    cin >> i;
}

为什么在 char foo [] = { 'a', 'd' }; 情况下我有输出:

ad╠╠╠╠╠╠R8$1↑■╬

当数组像 char foo [] = "ad"; 这样初始化时,我有正常的输出 -ad - 这在第一种情况下是预期的。

这两个数组初始化有什么区别,为什么第一个数组的输出中有垃圾?

最佳答案

你需要字符串以空结尾

char foo [] = { 'a', 'd', '\0' };

字符串文字已经以 null 结尾。

§ 2.14.5 String Literals

8 Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char, where n is the size of the string as defined below, and has static storage duration

14 After any necessary concatenation, in translation phase 7, '\0' is appended to every string literal so that programs that scan a string can find its end.

关于c++ - 数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32949403/

相关文章:

c++ - 链接期间模板实例发生冲突

c++ - 在安装 VS 2015 安装程序项目时安装 vcredist_x64.exe

c++ - 如何替换角色?

C++ 异常未在线程中处理

c++ - 无法将 'std::basic_istream<char>' 左值绑定(bind)到 'std::basic_istream<char>&&'

c++ - 部署后,简单的C++ ofstream项目无法正常工作

c++ - VS2010 中的 "redefinition; different type modifier"

c++ - 如何用不同大小的 vector 初始化二维 vector

python - python GUI的问题

c - 如何获取指向 MSVC 中二进制部分的指针?