Search code examples
c++c-strings

Why printing the array of strings does print first characters only?


Please explain the difference in the output of two programs.

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

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;
}

Program 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;
}

Solution

  • When you declare a const char* with assignment operator, for example:

    const char* some_string = "some text inside";
    

    What actually happens is the text being stored in the special, read-only memory with added the null terminating char after it ('\0'). It happens the same when declaring an array of const char*s. Every single const char* in your array points to the first character of the text in the memory.

    To understand what happens next, you need to understand how does std::cout << work with const char*s. While const char* is a pointer, it can point to only on thing at a time - to the beginning of your text. What std::cout << does with it, is it prints every single character, including the one that is being pointed by mentioned pointer until the null terminating character is encountered. Thus, if you declare:

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

    Your computer will allocate read-only memory and assign bytes to hold "text\0" and make your s point to the very first character (being 't').

    So far so good, but why does calling std::cout << *s output only a single character? That is because you dereference the pointer, getting what it points to - a single character.

    I encourage you to read about pointer semantics and dereferencing a pointer. You'll then understand this very easily.

    If, by any chance, you cannot connect what you have just read here to your example:

    Declaring const char* branch[4]; you declare an array of const char*s. Calling branch[0] is replaced by *(branch + 0), which is derefecencing your array, which results in receiving a single const char*. Then, if you do *branch[0] it is being understood as *(*(branch + 0)), which is dereferencing a const char* resulting in receiving a single character.