字符串赋值给指针与数组的区别
来源:互联网 发布:php程序员要求 编辑:程序博客网 时间:2024/06/05 02:11
代码
int Test() { // Test1 char str1[] = "hello world"; char str2[] = "hello world"; if (str1 == str2) cout << "str1 equal str2" << endl; else cout << "str1 is not equal to str2" << endl; char *pstr1 = "hello world"; char *pstr2 = "hello world"; if (pstr1 == pstr2) cout << "pstr1 equal to pstr2" << endl; else cout << "pstr1 is not equal to str2" << endl; // Test2 char str3[12]; str3 = "hello world"; //error char *pstr3; pstr3 = "hello world"; return 0;}
Test1结果:
str1 is not equal to str2
pstr1 equal pstr2
分析 :
在C++中,常量字符串存储于一块特殊的存储区且仅有一份拷贝,当为pstr1和pstr2赋值相同的字符串常量时候,他们实际上指向相同的内存地址。
但用常量初始化数组,情况有所不同。对于数组初始化来说,字符串常量相当于构造函数中的初始化列表,当初始化数组时,会为数组分配相应长度的空间,并把字符串常量复制到数组中去。str1和str2的初始地址不同,因此它们的值也是不同的。
两者类似浅拷贝与深拷贝。
Test2结果:
为str3赋值时候会报错,pstr3却不会。
分析:
因为str3是数组名,是指针常量,不能修改。
pstr3是普通指针,赋值时,指向内存中的字符串常量的地址。
阅读全文
0 0
- 如何理解字符串赋值给指针与数组的区别
- 字符串赋值给指针与数组的区别
- iOS 日记2 --字符串赋值给指针与数组的区别
- 字符串数组与字符串指针的区别
- 字符串指针与字符串数组的区别
- 给字符指针赋值, ” “双引号与' '单引号的区别
- 字符串数组/字符串指针的赋值
- 关于数组给指针赋值的问题
- 字符串指针与字符数组的区别
- 字符串指针与字符数组的区别
- 字符串指针与字符数组的区别
- 字符串指针与字符数组的区别
- 字符串指针与字符数组的区别
- 字符串指针与字符数组的区别
- 字符串指针与字符数组的区别
- 字符串指针与字符数组的区别
- 字符串指针与字符数组的区别
- 字符串指针与字符数组的区别
- python 下的 word2vec 学习笔记
- poj2192 Zipper
- 1037. Magic Coupon (25)
- 如何实现一篇学术文章的代码?
- LeetCode Weekly Contest 47
- 字符串赋值给指针与数组的区别
- thinkphp操作mysql之SQl语句报错及解决方案
- 从神经网络到深度学习(一 )
- JRadioButton(单选按钮)组件使用
- leetcode 7 Reverse Integer
- 设计模式_建造者模式(6)
- Python---1.序列通用操作
- [Java多线程 一]---线程的概念与基本性质
- SpringBoot项目API文档工具-Springfox Swagger