本文介绍了Sizeof字符串字面量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码
#include< iostream>
using namespace std;
int main()
{
const char * const foo =f;
const char bar [] =b;
cout<< sizeof(string literal)=< sizeof(f)<< endl;
cout<< sizeof(const char * const)=< sizeof(foo)< endl;
cout<< sizeof(const char [])=< sizeof(bar)< endl;
}
输出
sizeof(string literal)= 2
sizeof(const char * const)= 4
sizeof(const char [])= 2
$ c
<$> $ b> li>为什么 sizeof
计算字符串文字的长度(所需的空间)
- 字符串文字有不同的当给予
sizeof
?
解决方案
-
sizeof(f)
必须返回2,一个用于'f'在32位计算机上返回4,在64位计算机上返回8。 因为foo是一个指针
-
sizeof(bar)
返回2,因为bar是两个字符的数组,'b'和
字符串文字的类型为'char'的大小N的数组,其中N包括
请记住,数组传递给 sizeof
时不会衰减指针。
The following code
#include <iostream>
using namespace std;
int main()
{
const char* const foo = "f";
const char bar[] = "b";
cout << "sizeof(string literal) = " << sizeof( "f" ) << endl;
cout << "sizeof(const char* const) = " << sizeof( foo ) << endl;
cout << "sizeof(const char[]) = " << sizeof( bar ) << endl;
}
outputs
sizeof(string literal) = 2
sizeof(const char* const) = 4
sizeof(const char[]) = 2
on a 32bit OS, compiled with GCC.
- Why does
sizeof
calculate the length of (the space needed for) the string literal ? - Does the string literal have a different type (from char* or char[]) when given to
sizeof
?
解决方案 sizeof("f")
must return 2, one for the 'f' and one for the terminating '\0'.sizeof(foo)
returns 4 on a 32-bit machine and 8 on a 64-bit machine because foo is a pointersizeof(bar)
returns 2 because bar is an array of two characters, the 'b' and the terminating '\0'.
The string literal has the type 'array of size N of char' where N includes the terminal null.
Remember, arrays do not decay to pointers when passed to sizeof
.
这篇关于Sizeof字符串字面量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!