某日二师兄参加XXX科技公司的C++工程师开发岗位第10面:
面试官:了解
sizeof操作符吗?二师兄:略微了解(不就是求大小的嘛。。)
面试官:请讲以下如何使用
sizeof?二师兄:
sizeof主要是求变量或者类型的大小。直接使用sizeof(type)或sizeof(var)即可。面试官:嗯。
sizeof(int*)、sizeof(int**)和sizeof(int[4])各返回什么?二师兄:前两者的返回值相等。在32位操作系统中返回4,64位操作系统中返回8。
sizeof(int[4])返回16,是因为sizeof运算时数组不会退化为指针。面试官:如果一个
int* p = nullptr,那么对其进行sizeof(*p)会发生什么?二师兄:返回4。原因是
sizeof在编译时求值,sizeof只需要获取*p的类型,并不对*p求值。所以不会发生段错误。面试官:下面三个
szieof运算符,各返回什么?
#include <iostream> #include <string> int main(int argc, char const *argv[]) { const char* str1 = "hello"; char str2[] = "hello"; std::string str3 = "hello"; std::cout << sizeof(str1) << std::endl; std::cout << sizeof(str2) << std::endl; std::cout << sizeof(str3) << std::endl; }
二师兄:第一个返回4或8,因为它是个指针,第二个是个数组,不过末尾有个