Sizeof string literal

C++StringSizeof

C++ Problem Overview


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 ?

C++ Solutions


Solution 1 - C++

  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 const char' where N includes the terminal null.

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

Solution 2 - C++

sizeof returns the size in bytes of its operand. That should answer question number 1. ;) Also, a string literal is of type "array to n const char" when passed to sizeof.

Your test cases, one by one:

  • "f" is a string literal consisting of two characters, the character f and the terminating NUL.
  • foo is a pointer (edit: regardless of qualifiers), and pointers seem to be 4 bytes long on your system..
  • For bar the case is the same as "f".

Hope that helps.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCsTamasView Question on Stackoverflow
Solution 1 - C++Jonathan LefflerView Answer on Stackoverflow
Solution 2 - C++Michael FoukarakisView Answer on Stackoverflow