1

In the following program the string stored is changed using cin, thus changing address. The address of the first element of string is represented by s. The address of the first element is the string itself. Thus it got changed when new string is entered. When I try to output &s[0] to cout it gives the whole string.

#include<iostream>
using namespace std;
int main() {
    char s[6];
    cin >> s;   // say abcde
    cout << s ; 
    cout << &s[0] ; // gives abcde

    cin >> s;   // say stack 
    cout << s;  
    cout << &s[0] ; gives stack
}
SleuthEye
  • 14,379
  • 2
  • 32
  • 61
cs-dev
  • 107
  • 10

1 Answers1

2

The address is not changing, the data stored at the address is changing. The reason the whole string's getting printed is because you're passing a pointer to cout, and an array can be passed to a function (or a stream) by giving a pointer to the first item. Passing a pointer to the first char is like passing a C-style string. If you want to print the address of the first char then you need to cast the pointer to void*: cout<<(void*)&s[0] (this will print the address of the first char).

Quentin
  • 62,093
  • 7
  • 131
  • 191