经典问题之[]和*真的完全一样吗?

通常,当我们定义:一个字符串时候,会采用下面两种方式:

1 char str[] = “hello world!2 char*  str = “hello world!”

通常我们会认为上面两行代码表达的含义是相同的,甚至完全等价。

我们看下面一段代码:

 1 int main()
 2 {
 3       char s1[] = "no hello world!";
 4     char  s2[] = "no hello world!";
 5          char  *s3 = "no hello world!";
 6          char  *s4 = "no hello world!";
 7     if(s1 == s2)
 8     {
 9         cout << "s1 == s2"<<endl;
10     }
11     else{cout<< "s1 != s2"<<endl;}
12     if(s3 == s4)
13     {
14         cout << "s3 == s4"<<endl;
15     }
16     else{cout<< "s3 != s4"<<endl;} 
17 
18 }

我们看一下输出结果:

s1 != s2
s3 == s4

这表明,对于*和[]表述的含义是完全不同的。

       当我们采用:char s1[] = "no hello world!";来定义字符串数组的时候,会为数组变量 s1开辟数组空间,将这些字符装进去。当定义 char s2[]的时候,会为重新声明的变量s2开辟另一块地址不同的空间

    当我们采用:char *s1 = "no hello world!";来定义字符串数组的时候,本质上是相当于先产生了一个字符串常量,这个常量放在一个固定的字符串常量区,而后只是将定义的指针指向了这个地址。而后即使再定义char *s2 = "no hello world!",也只是将s2指向了这个固定的地址。即当我们用字符指针的方式定义字符串的时候,整个 “hello world!”本质上代表一个地址,也就是,当我们看到"hello world!",我们看到的应该是一个地址,而不是字符串本身

posted @ 2020-01-16 16:22  少年π  阅读(410)  评论(0编辑  收藏  举报