Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

c++ - Sizeof string literal

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 ?
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. sizeof("f") must return 2, one for the 'f' and one for the terminating ''.
  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 ''.

The string literal has the type 'array of size N of const char' where N includes the terminal null.

Remember, arrays do not decay to pointers when passed to sizeof.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...