最近找工作,不免有些笔试,有些会涉及到c和c++,本文主要谈谈sizeof。
从例子谈起吧。
- struct A
- {
- int i;
- char c;
- };
问sizeof(A)结果是多少?
插一句,本文并不旨在讨论sizeof的运算结果。
最常见的题型莫过于此。究竟等于几呢?我猜是8,编译运行结果的确是8(手头有个vs2008,别的编译器没试)。为什么是8不是5,一定有许多人可以回答,此处就不赘述。
笔者想说的是,到底sizeof的作用是什么?写段代码:
- int *pointer; /*pointer to type int, used to reference our allocated data*/
- pointer = malloc(sizeof(int) * 10);
上面的代码作用是分配10个int类型大小的空间,动态分配数组时常用的办法。
为什么不直接写malloc(4 * 10)呢,我可以算出来sizeof(int)的。到此,大家应该明白我想说什么了。对,究竟我们为什么要知道4?
引用《C++ Programming Language》中的一些话(Section 4.6, 75)
“Some of the aspects of C++’s fundamental types, such as the size of an int, are implementation-defined.”
C++基本类型的某些方面,比如int的大小,是实现定义的。
“People who claim they don’t care about portability usually do so because they use only a single system and feel they can afford the attitude that "the language is what my compiler
implements." This is a narrow and shortsighted view.”
不关心移植性的人通常这么做,因为他们只使用单一的系统并且有种看法,就是“语言就是编译器实现的东西”,这是狭隘且目光短浅的看法。
既然sizeof的出现是避免我们写出4,为什么还要知道4甚至前面的8呢?
只是为了区别菜鸟与高手吗?