sizeof与strlen的区别 浅谈

1、sizeof operator

sizeof是C语言的一种单目操作符,如C语言的其他操作符++、- - 等,它并不是函数.
Queries size of the object or type.

1) returns size in bytes of the object representation of type.
2) returns size in bytes of the object representation of the type, that would be returned by expression, if evaluated.

Syntax
sizeof(type)(1)
sizeof expression(2)

struct Empty {};
struct Base { int a; };
struct Derived : Base { int b; };
struct Bit {unsigned bit:1; };
int main(){
    Empty e;
    Derived d;
    Base& b = d;
    Bit bit;
    std::cout<< "size of empty class: "     << sizeof e        << '\n'
             << "size of pointer : "        << sizeof &e       << '\n'
//           << "size of function: "        << sizeof(void())  << '\n'  // compile error
//           << "size of incomplete type: " << sizeof(int[])   << '\n'  // compile error
//           << "size of bit field: "       << sizeof bit.bit  << '\n'  // compile error
             << "size of array of 10 int: " << sizeof(int[10]) << '\n'
             << "size of the Derived:     " << sizeof d << '\n'
             << "size of the Derived through Base: " << sizeof b << '\n';
}
size of empty class: 1
size of pointer : 8
size of array of 10 int: 40
size of the Derived:     8
size of the Derived through Base: 4

参考自 cppreference.com


2、strlen

size_t strlen ( const char * str );

Get string length
Returns the length of the C string str.
"\0"结束,不包含"\0"

mystr[100]="test string";
sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.

参考自 cplusplus.com


以上两个都不怎么用到,面试的时候问起,自己不是十分了解,遂查资料。

转载于:https://www.cnblogs.com/iois/p/4896901.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值