c++ - 为什么打印字符串数组只打印第一个字符?

标签 c++ c-strings

请解释两个程序的输出差异。

cout << branch[i]在第一个程序中输出如下:

Architecture
Electrical
Computer
Civil

cout << *branch[i] in second program gives output as:

A
E
C
C

Why?

What is the logic behind *branch[i] giving only first character of each word as output and branch[i] giving full string as an output?

Program 1

#include <iostream>

using namespace std;

int main()
{
    const char *branch[4] = { "Architecture", "Electrical", "Computer", "Civil" };

    for (int i=0; i < 4; i++) 
        cout << branch[i] << endl;

    system("pause");
    return 0;
}

程序 2

#include <iostream>

using namespace std;

int main()
{
    const char *branch[4] = { "Architecture", "Electrical", "Computer", "Civil" };

    for (int i=0; i < 4; i++) 
        cout << *branch[i] << endl;

    system("pause");
    return 0;
}

最佳答案

当你声明一个 const char*使用赋值运算符,例如:

const char* some_string = "some text inside";

实际发生的是将文本存储在特殊的只读存储器中在其后添加空终止字符 ('\0')。声明 const char* 的数组时,情况相同秒。每单const char*在你的数组中指向内存中文本的第一个字符

要了解接下来会发生什么,您需要了解 std::cout << 是如何实现的与 const char* 一起工作秒。同时 const char*是一个指针,它一次只能指向一个东西——指向文本的开头。什么std::cout <<用它做,它是否打印每个字符,包括提到的指针指向的字符直到遇到空终止字符。因此,如果您声明:

const char* s = "text";
std::cout << s;

您的计算机将分配只读内存并分配字节来保存 "text\0"并让你的s指向第一个字符(即 't' )。

到目前为止一切顺利,但为什么调用 std::cout << *s只输出一个字符?那是因为您取消引用 指针,得到它指向的内容 - 单个字符。

我鼓励您阅读有关指针语义和取消引用指针的内容。然后你会很容易理解这一点。

如果您碰巧无法将此处阅读的内容与您的示例联系起来:

声明const char* branch[4];你声明了一个 const char* 的数组秒。打电话branch[0]*(branch + 0) 取代,这是对您的数组的取消引用,这导致收到单个 const char* .然后,如果你做 *branch[0]它被理解为*(*(branch + 0)) ,这是取消引用 const char* 导致接收到单个字符。

关于c++ - 为什么打印字符串数组只打印第一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46552139/

相关文章:

c - 'fopen' 将如何解释一个容量大于它包含的字符串的 'char[]'?

c++ - 在c++中添加两个c字符串

c++ - 不明白为什么我会收到异常 : Access violation reading location 0x00000000

c++ - 静态库、链接和依赖

c++ - 导入 ctype;在 C++ 应用程序中嵌入 python

c++ - operator<< 找不到匹配项

c++ - OpenCV手部检测?

c++ - 如何附加不同的文件并提取它们以在我的代码中进行验证?

c - strlen函数的理解——const char *s赋值给const char *sc

c++ - 从 c 字符串中删除空格和特殊字符