C ++ Char Array指针行为vs字符串数组指针

时间:2017-09-10 23:35:18

标签: c++ arrays string pointers implicit-conversion

C ++ Rookie第一个问题。使用代码:块16.01 GNU GCC编译器。 提前致谢。码;

#include <iostream>
using namespace std; 

int main(){
    char charArr[]="Hello";
    cout<<charArr<<endl;  //outputs Hello.

    string strArr[]={"Hello", "Stack", "overflow"};
    string *pStrArr=strArr; //pointer to strArr; same as &strArr[0].
    cout<<*pStrArr<<endl; //Derreferencing pointer , outputs Hello

    char charArr1[]="Hello";
    char *pCharArr1=charArr1;  /*pointer to charArr1.(charArr cout was Hello, not H, therefore i assumed we are storing in memory Hello);*/
    cout<<*pCharArr1<<endl;  /*dereferencing, outputs H, not Hello as i expected. */

    return 0; 
}

观察; charArr输出Hello,因此我假设创建一个指针并取消引用它应该输出Hello;实际输出为H,这似乎与在字符串数组上观察到的行为不一致,而第一个元素是指向和解除引用的。

问题是: 很明显,我无法理解char Array。我将非常感谢(尽可能)外行条款对上述内容的解释。

PS:确实使用了搜索功能并与Duck交谈。谢谢你的时间。 ++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++ 在所有答案之后,我意识到实际问题应该是为什么第2行和第4行产生不同的输出,strArr是一个内存地址(表现为指针),而charArr输出数组内容。

string strArr[]= {"hello","world","how", "are","you"};
cout<<strArr<<endl;//outputs 0x28fedc.

char charArr[]="Hello";
cout<<charArr<<endl; // outputs hello

谢谢

1 个答案:

答案 0 :(得分:1)

在此代码段中

char charArr1[]="Hello";
char *pCharArr1=charArr1;  /*pointer to charArr1.(charArr cout was Hello, not H, therefore i assumed we are storing in memory Hello);*/
cout<<*pCharArr1<<endl;  /*dereferencing, outputs H, not Hello as i expected. */

对象pCharArr1的类型为char *。它指向存储在数组"Hello"中的字符串charArr1的第一个字符。取消引用指针,您将获得类型为char的对象,该对象是指针指向的字符。它是角色'H'

在此代码段中

string strArr[]={"Hello", "Stack", "overflow"};
string *pStrArr=strArr; //pointer to strArr; same as &strArr[0].
cout<<*pStrArr<<endl; //Derreferencing pointer , outputs Hello

对象pStrArr的类型为std::string *,并指向std::string类型的对象。取消引用指针,您将获得包含字符序列std::string的{​​{1}}类型的对象。所以在这个声明中

"Hello"

输出此序列。

因此在本声明中

cout<<*pStrArr<<endl; //Derreferencing pointer , outputs Hello

cout<<charArr<<endl; //outputs Hello 的类型为charArr(数组指示符隐式转换为指向其第一个元素的指针)。

在本声明中

char *

cout<<*pCharArr1<<endl; /*dereferencing, outputs H, not Hello as i expected. */ 的类型为*pCharArr1

最后在本声明中

char

cout<<*pStrArr<<endl; //Derreferencing pointer , outputs Hello 的类型为*pStrArr

考虑到这些声明

std::string

这些陈述的输出

char charArr1[]="Hello";
char *pCharArr1=charArr1;  /*pointer to charArr1.(charArr cout was Hello, not H, therefore i assumed we are storing in memory Hello);*/

cout<<CharArr1<<endl;  

将相同,并且将等于输出字符串cout<<pCharArr1<<endl;

但是对于这些陈述

"Hello"

cout<<*CharArr1<<endl;  

只输出一个字符cout<<*pCharArr1<<endl;

在提到的第一个语句中,数组指示符被隐式转换为指向表达式'H'

中第一个元素的指针
相关问题