Click here to Skip to main content
15,901,035 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. Can someone explain me why this two line of codes doesnt output the same result ?

C++
char* str = "hello world";

cout << sizeof(str) << endl;  //output: 4
cout << sizeof("hello world") << endl;  //output: 12


edit: and how can I retrieve the size of a string using the pointer ?
Posted
Updated 18-May-14 1:57am
v2
Comments
[no name] 18-May-14 7:12am    
Because the sizeof of a char pointer is 4.
Kornfeld Eliyahu Peter 18-May-14 7:15am    
This IS the answer, so post it that anyone should profit from this...
M­­ar­­­­k 18-May-14 7:20am    
So is there anyway to calculate the size of the string using pointers ?
sizeof(*str) doesnt work.
Kornfeld Eliyahu Peter 18-May-14 7:24am    
Use strlen(str) for that...
M­­ar­­­­k 18-May-14 7:26am    
but strlen is for calc the length o_O
I want to calc the size not the length !

1 solution

Remember that the original C++ was defined before Unicode programming became a request.
The char type is always a byte size so a 12 letter long string will take up 12 bytes...
If you want to use Unicode you have to use wchar_t type and the corresponding functions like wcslen()...
But of course wcslen(0 returns the length in the units of the type so if you want to know the byte size you have to multiply it with sizeof(wchar_t)...
C++
wchar_t* str = L"hello world";
 
cout << wcslen(str) << endl;  // 12
cout <<  wcslen(str) * sizeof(wchar_t) << endl;  // probably 24, but depends on implementation
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900