您的位置:首页 > 编程语言 > C语言/C++

【基础知识】c++字符串中需要注意的一些细节

2010-03-01 11:50 906 查看
学了1年Java了,突然又要转向C++,悲叹之余还是要复习一下原本就不是很熟悉的C++语法。

代码:

代码

1 char* cs = "hello";
2 char ca[] = "hello";
3 char* pca[] = {"hw", "h", "h"};
4
5 cout << endl << "print cs....." << endl;
6
7 cout << cs << endl;
8 cout << *cs << endl;
9 cout << sizeof(cs) << endl;
10 cout << sizeof(*cs) << endl;
11
12 cout << endl << "print ca...." << endl;
13
14 cout << ca << endl;
15 cout << *ca << endl;
16 cout << sizeof(ca) << endl;
17 cout << sizeof(*ca) << endl;
18
19 cout << endl << "print pca ..." << endl;
20
21 cout << pca << endl;
22 cout << *pca << endl;
23 cout << sizeof(pca) << endl;
24 cout << sizeof(*pca) << endl;

执行结果:



其中有三点需要自己注意:

一: 第7行,尽管cs是个指针,存储的是"hello"字符串在内存中的首地址(即'h'的地址),但是,向标准输出打印时,输出的并不是地址值,而是整个字符串。有别于其他类型.

二: 第14行:当打印数组名时,一般情况下,将会输出数组的首地址,如第21行。但有个特列是,当打印字符串数组的数组名,输出的将是整个字符串。如14行。

三: 关于sizeof运算符的使用:引用csdn中一段话

When you apply the sizeof operator to an array identifier, the result is the size of the entire array rather than the size of the pointer represented by the array identifier.

  当将sizeof运算符运用到数组名的时候,返回的结果将是整个数组的大小,而不是代表数组的那个指针的大小。

所以, 16行和第23行的输出也就一目了然了。16行的ca数组保存着"hello" 5个字符,和最后一个自动添加的"\0",共6个字符,每个字符占有1byte,所以共有6byte。 23行的pca数组,保存着3个地址值,分别指向三个字符串,每个地址值是个32bit的整形,所以3个地址值共占用12个字节的空间。

另外,csdn中针对sizeof还有另外一段叙述,需要注意:

When you apply the sizeof operator to a structure or union type name, or to an identifier of structure or union type, the result is the number of bytes in the structure or union, including internal and trailing padding. This size may include internal and trailing padding used to align the members of the structure or union on memory boundaries. Thus, the result may not correspond to the size calculated by adding up the storage requirements of the individual members.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: