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


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

  • 相关阅读:
    C#等同于正则表达式的写法
    操作XML
    对比工具集合
    IIS 部署的网站无法启动
    jdk_1.8 下载之后的配置
    sql server 2008认识 DENSE_RANK
    c# 二分查找算法
    c# 使用栈实现有效的括号
    sql server 自定义标量函数
    虚拟机cenos 重置密码
  • 原文地址:https://www.cnblogs.com/iois/p/4896901.html
Copyright © 2011-2022 走看看