简体   繁体   English

如何获得一个指向字符数组中第一个字符的常量指针?

[英]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. 在以下程序中,使用cin更改了存储的字符串,从而更改了地址。 The address of the first element of string is represented by s . 字符串的第一个元素的地址由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. 当我尝试输出&s[0]cout它给整个字符串。

#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. 整个字符串被打印的原因是因为您传递了一个指向 cout指针 ,并且可以通过提供一个指向第一项的指针来将数组传递给一个函数(或流)。 Passing a pointer to the first char is like passing a C-style string. 将指针传递给第一个char就像传递C样式字符串。 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). 如果要打印第一个字符的地址,则需要将指针cout<<(void*)&s[0]void*cout<<(void*)&s[0] (这将打印第一个字符的地址)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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