sizeof第二次认识

开始我的问题是

char intArray[]="wo shi shui";
int len=sizeof intArray;
cout<<len<<endl;
输出的是12
char *intArray="wo shi shui";
int len=sizeof intArray;
cout<<len<<endl;
输出的是4

为什么一个输出的是12,一个输出的是4.因为我条件反射地认为可以通过sizeof和一个字符串的指针去获得该字符串的长度,但是情况就象上面的出现的那样,用指针是不能获得字符串的长度的,只能返回该指针的字节数.

分析其原因:个人认为 指针是一个变量,不能用sizeof去获得一个变量的长度,所以这样只能获得给变量 类型的长度.

下面是MSDN上的 列子

sizeof  :The sizeof operator yields the size of its operand with respect to the size of type char

When the sizeof operator is applied to an object of type char, it yields 1. When the sizeof operator is applied to an array, it yields the total number of bytes in that array, not the size of the pointer represented by the array identifier. To obtain the size of the pointer represented by the array identifier, pass it as a parameter to a function that uses sizeof

#include <iostream>

size_t getPtrSize( char *ptr )
{
   return sizeof( ptr );
}

using namespace std;
int main()
{
   char szHello[] = "Hello, world!";

   cout  << "The size of a char is: "
         << sizeof( char )
         << "/nThe length of " << szHello << " is: "
         << sizeof szHello
         << "/nThe size of the pointer is "
         << getPtrSize( szHello ) << endl;
}
Output
The size of a char is: 1
The length of Hello, world! is: 14
The size of the pointer is 4
上面的都是引用MSDN上的

通过sizeof的操作可以获得关于char型的操作数的大小.

当sizeof用于操作char对象它返回1,当sizeof应用于数组它返回整个数组的字节数,而不是用于定义数组指针的打下(即不是指针类型的的字节数,在32位操作系统指针的字节树是4),用指针的作为参数可以获得指针的大小.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值