简体   繁体   中英

How can you get a constant pointer to the first char in a character array?

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
}

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM