zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    MySQL存储过程
    [转载]JDBC应该始终以PreparedStatement代替Statement
    Restlet入门例子 RESTful web framwork for java
    Cglib的使用方法(3)Mixin
    HDOJ_1220
    精华:OracleHelper类
    web.config详解
    ADO.NET结构
    字典树
    WCF、Net remoting、Web service概念及区别
  • 原文地址:https://www.cnblogs.com/johnpher/p/2570623.html
Copyright © 2011-2022 走看看