zoukankan      html  css  js  c++  java
  • 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        << '
    '
                 << "size of pointer : "        << sizeof &e       << '
    '
    //           << "size of function: "        << sizeof(void())  << '
    '  // compile error
    //           << "size of incomplete type: " << sizeof(int[])   << '
    '  // compile error
    //           << "size of bit field: "       << sizeof bit.bit  << '
    '  // compile error
                 << "size of array of 10 int: " << sizeof(int[10]) << '
    '
                 << "size of the Derived:     " << sizeof d << '
    '
                 << "size of the Derived through Base: " << sizeof b << '
    ';
    }
    
    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.
    ""结束,不包含""

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

    参考自 cplusplus.com


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

  • 相关阅读:
    还不知道spring的RestTemplate的妙用吗
    【学习笔记】机器学习之特征工程
    《饥饿的盛世》总结
    我是如何解决java.security.cert.CertPathValidatorException异常的
    《机器学习
    2018年总结
    元类实现ORM
    元类
    python中的装饰器
    python中的闭包
  • 原文地址:https://www.cnblogs.com/iois/p/4896901.html
Copyright © 2011-2022 走看看