Pointer printing first char of string

802 views Asked by At
#include <iostream>

using namespace std;
char* input(char **S);
int main()
{
    char **S = new char *; 
    char *K = input(S);
    //cout << K << endl;
    cout << *K << endl;
}

char* input(char **S)
{
    cout << "Enter string: ";
    cin >> *S;
    cout << S << endl; // Prints address of S
    cout << *S << endl; //Prints content of address stored in S
    return *S;
}

I am failing to understand why when I print out *K, I just get the first character of the input string but if I print out the commented line(just K alone) I get the whole string. Any help with explaining what I am not able to see or understand is appreciated.

1

There are 1 answers

2
Vaibhav On

Let's understand how arrays work:

// Let's say I have one character array
char arr[] = {'a', 'b', 'c', 'd'};

In here, the name of the array i.e. arr acts as the pointer to the first element of the array. However, do note that it is NOT the pointer to the first element to avoid confusion, it just have an implicit conversion to pointer of element type. More details can be found here: https://stackoverflow.com/a/1641963/10821123

Now since array is contiguous, the rest of the elements can be determined.

// so ideally, the below two statements would print the same thing
cout << &arr << endl;
cout << (void*) &arr[0] << endl;
// the above line just takes out the address of the first pointer

Now coming to your question, I'll convert my example to a string one:

char *K = "abc";

cout << *K << endl; // a
cout << K << endl; // abc

Note that the above assignment of char *K = "abc"; will give you a warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]

The pointer only holds the address of the first element of the array, so when you dereference the pointer, it prints the first element, i.e. *K is interpreted as K[0]

Now there's an overload of operator <<, so what it does is if it sees a character pointer i.e. char*, it prints the complete null-terminated string, that's why in your case too, it is printing the whole string.