#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.
Let's understand how arrays work:
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.
Now coming to your question, I'll convert my example to a string one:
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.
*Kis interpreted asK[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.