Sizeof字符串字面量

Sizeof字符串字面量

本文介绍了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

    <$>

    $ b>

    li>为什么 sizeof 计算字符串文字的长度(所需的空间)
  1. 字符串文字有不同的当给予 sizeof


解决方案

  1. sizeof(f)必须返回2,一个用于'f'在32位计算机上返回4,在64位计算机上返回8。

  2. 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.

  1. Why does sizeof calculate the length of (the space needed for) the string literal ?
  2. Does the string literal have a different type (from char* or char[]) when given to sizeof ?
解决方案
  1. sizeof("f") must return 2, one for the 'f' and one for the terminating '\0'.
  2. sizeof(foo) returns 4 on a 32-bit machine and 8 on a 64-bit machine because foo is a pointer
  3. sizeof(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字符串字面量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:43