-1

I am little confused about the use of & literal with strings. I see a big difference in the output of following two codes:

#include <iostream>
using namespace std;
int main() 
{
    char st[]="This is a Sample String";
    cout<<st[0];
    return 0;
}

Output: T

#include <iostream>
using namespace std;
int main() 
{
    char st[]="This is a Sample String";
    cout<<&st[0];
    return 0;
}

Output: This is a Sample String

I know & is used as a reference operator to pass the value by reference. But my question is how & actually works here.

Biffen
  • 6,249
  • 6
  • 28
  • 36
  • 5
    The character "&" has several different meanings. The `&` operator applied to an expression creates a pointer, not a reference. The `&` you see in reference types is not an operator. – molbdnilo Apr 21 '18 at 06:53
  • 2
    In the example you have shown, `&` is the "address of" operator. It obtains the address of its operand, in this case the operand is `st[0]` and `&st[0]` gives the address of the first character in `st`. `cout`s `operator<<()` is overloaded to accept a `const char *`, which it interprets as the address of the first character of a zero-terminated string (which is what `st` contains). – Peter Apr 21 '18 at 07:45
  • 1
    @Peter that should be an answer. – Jesper Juhl Apr 21 '18 at 08:21
  • Thanks @Peter. It really helped. – sahilsharma811 Apr 22 '18 at 15:57

1 Answers1

0

Array of characters is also called string in C++. And in C++ if you want to print the Starting address of the string then it will not print the starting address of the string it will print the whole string.

The operator& have different meaning in different situation in C++. And the meaning of & is decided by its context(where it is using).

Muhammad Usman
  • 1,220
  • 13
  • 22
  • ‘*Array of characters is also called string in C++.*’ Debatable. A ‘string’ in C++ is something else to most people. – Biffen Apr 21 '18 at 18:54
  • you are right but for the beginners the basic info is engouh... i don't want to make confuse to sahilsharma811 .. – Muhammad Usman Apr 21 '18 at 19:52