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


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

原文地址:https://www.cnblogs.com/iois/p/4896901.html