sizeof char数组问题 [英] sizeof char array problem

查看:105
本文介绍了sizeof char数组问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。有人可以解释一下为什么这两行代码没有输出相同的结果吗?



Hi. Can someone explain me why this two line of codes doesnt output the same result ?

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 ?

推荐答案

请记住,原始C ++是在Unicode编程成为之前定义的一个要求。

char类型总是一个字节大小,所以12个字母长的字符串将占用12个字节...

如果你想使用Unicode,你必须使用wchar_t类型和wcslen()相对应的函数...

当然wcslen(0以类型为单位返回长度,所以如果你想知道字节大小你需要将它与sizeof相乘(wchar_t)...

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)...
wchar_t* str = L"hello world";
 
cout << wcslen(str) << endl;  // 12
cout <<  wcslen(str) * sizeof(wchar_t) << endl;  // probably 24, but depends on implementation


这篇关于sizeof char数组问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆