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

C++字符串两个需注意的地方

2008-03-09 11:20 190 查看
1.访问单个字符
可以通过下标操作符"[]"或者成员函数"at()"访问单个字符。不同之处在于, [] 不会进行范围检查,而at() 会进行范围检查。也就是说,当访问一个不存在的字符位置时,采用 [] 将会获得不可预知的结果。若采用的是 "at()" 访问一个不存在的字符位置,程序将会中止。

2. sizeof
sizeof 可获得 string 的长度。所有的 string 类型调用 sizeof 都将返回相同的值 4.(在另外一些编译器中,有可能返回8)
可以这样理解:
class string
{
char* pstr;
...
}
每次调用 sizeof(string) 其实就等价于调用 sizeof(char*),返回一个char型指针的内存字节数。
不仅是 char* 型指针 返回 4,所有的指针类型使用 sizeof 都回返回相同的结果 4
sizeof( string* ) = 4
sizeof( int* ) = 4
sizeof( char* ) = 4

另外有点迷惑的地方,对非string的字符串用sizeof有完全不同的结果:
sizeof( "hello" ) = 6
sizeof( "hello there" ) = 12
这是因为, 字符串"hello"并不是作为一个string对象存储,其内部表示是一个以'/0'字符结尾的字符数组。其等价于:
char s[] = "hello";
sizeof( s ) ;// 返回数组所占空间容量, 6个字节

还有一个需要注意的是,当把 数组 作为参数传入到函数中以后,在函数中调用 sizeof 将不会得到数组的所占空间容量。

int main()
{
int array[50] = {1,2,3,4,5};
int size1 = sizeof( array ) / sizeof( array[0] ); // size1 = 50
test( array );
}
void test( int array[] )
{
int size2 = sizeof( array ) / sizeof( array[0] ); // 注意: size2 = 1
}
size2的值为1是因为,当数组名作为函数的参数时,它将严格的被当作指针看待。sizeof( array )等价于
sizeof( int* ),其值为4。同时,分母 sizeof( array[0] )也将返回4。

MSDN上sizeof定义:
sizeof Operator
sizeof expression
The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t. The expression is either an identifier or a type-cast expression (a type specifier enclosed in parentheses). When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated arrays or external arrays.
(只能获得静态数组的存储容量,无法获得动态数组的存储容量)

网上还看到另外一个例子,觉得不错,摘录如下:
char* ss = "0123456789";
sizeof(ss) 结果 4 ===》ss是指向字符串常量的字符指针
sizeof(*ss) 结果 1 ===》*ss是第一个字符
char ss[] = "0123456789";
sizeof(ss) 结果 11 ===》ss是数组,计算到/0位置,因此是10+1
sizeof(*ss) 结果 1 ===》*ss是第一个字符
char ss[100] = "0123456789";
sizeof(ss) 结果是100 ===》ss表示在内存中的大小 100×1
strlen(ss) 结果是10 ===》strlen是个函数内部实现是用一个循环计算到/0为止之前
int ss[100] = "0123456789";
sizeof(ss) 结果 400 ===》ss表示在内存中的大小 100×4
strlen(ss) 错误 ===》strlen的参数只能是char* 且必须是以/'0'结尾的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: