• sizeof()与strlen()的区别与联系


    从外部特性来看:


     

    两者最本质的区别在于sizeof是操作符,而strlen是函数。

    他们在MSDN中的定义分别为:

    sizeof Operator

    sizeof expression

    The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t.

    The expression is either an identifier or a type-cast expression (a type specifier enclosed in

    parentheses).

    When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated arrays or external arrays.

     -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    strlen

    Get the length of a string.

    Routine Required Header:

    strlen <string.h>

    size_t strlen( const char *string );

    Parameter

    string:Null-terminated string

    Libraries

    All versions of the C run-time libraries.

    Return Value

    Each of these functions returns the number of characters in string, excluding the terminal

    NULL. No return value is reserved to indicate an error.

    Remarks

    Each of these functions returns the number of characters in string, not including the

    terminating null character. wcslen is a wide-character version of strlen; the argument of

    wcslen is a wide-character string. wcslen and strlen behave identically otherwise.

    可见strlen是针对string的,而sizeof仅仅是一个keyword.

    大部分编译器在编译时就计算了sizeof的值,而strlen则是在程序执行过程中计算的。

    sizeof计算出的是该类型所占内存的大小,而strlen计算出的则是字符串的实际长度。

    Evaluating sizeof expr does not evaluate the expression.

    The result of applying sizeof depends in part on the type involved:

    l  sizeof char or an expression of type char is guaranteed to be 1

    l  sizeof a reference type returns the size of the memory necessary to contain an object of the referenced type

    l  sizeof a pointer returns the size needed hold a pointer; to obtain the size of the object to which the pointer pointers, the pointer must be dereferenced

    l  sizeof an array is equivalent to taking the sizeof the element type times the number of elements in the array

  • 相关阅读:
    gettid 和pthread_self的区别
    UDP socket也可以使用connect系统调用
    TCP协议中的SO_LINGER选项
    pthread_key_t和pthread_key_create()详解
    1、Window10 Electron 开发环境搭建
    如何查看Windows下端口占用
    Servlet 中使用POI生成Excel
    JdbcTemplate 操作Oracle Blob
    RedHat 6.5 离线安装 apache2.4.23
    windows下端口被占用的解决方法
  • 原文地址:https://www.cnblogs.com/johnpher/p/2570623.html
Copyright © 2020-2023  润新知