sizeof与strlen的区别 浅谈
1、sizeof operator
sizeof是C语言的一种单目操作符,如C语言的其他操作符++、- - 等,它并不是函数.
Queries size of the object or type.
- returns size in bytes of the object representation of type.
- 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 << '\n'
<< "size of pointer : " << sizeof &e << '\n'
// << "size of function: " << sizeof(void()) << '\n' // compile error
// << "size of incomplete type: " << sizeof(int[]) << '\n' // compile error
// << "size of bit field: " << sizeof bit.bit << '\n' // compile error
<< "size of array of 10 int: " << sizeof(int[10]) << '\n'
<< "size of the Derived: " << sizeof d << '\n'
<< "size of the Derived through Base: " << sizeof b << '\n';
}
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
2、strlen
size_t strlen ( const char * str );
Get string length
Returns the length of the C string str.
以"\0"结束,不包含"\0"
mystr[100]="test string";
sizeof(mystr) evaluates to 100, strlen(mystr) returns 11.
以上两个都不怎么用到,面试的时候问起,自己不是十分了解,遂查资料。