C++指针应用

来源:互联网 发布:超级数据恢复软件破解 编辑:程序博客网 时间:2024/05/16 07:07

int main()

{

  char str1[] = "hello world";

  char str2[] = "hello world";


  char* str3[] = "hello world";

  char* str4[] = "hello world";

   if(str1 == str2)

       printf("str1and str2 are same\n");

  else

     printf("str1 and str2 not same\n");


  if(str3==str4)

    printf("str3 and str4 are same\n");

  else

   printf("str3 and str4 not same");

}

分析:程序最终输出结果是str1 and str2 are same;str3 and str4 not same.

str1和str2是两个字符串数组,程序会为它们分配两个长度为12个字节的空间,并把hello world的内容分别复制到数组中去,这是两个初始地址不同的数组,因此str1 和str2的值也不相同。str3和str4是两个指针,我们无须为它们分配内存以存储字符串的内容,而只需要把他们指向hello world在内存中的地址就可以了,由于hello world是常量字符串,它在内存中只有一个拷贝,因此str3和str4指向的是同一个地址。

0 0