5.8. The sizeof Operator5.8. sizeof 操作符The sizeof operator returns a value of type size_t (Section 3.5.2, p. 104) that is the size, in bytes (Section 2.1, p. 35), of an object or type name. The result of sizeof expression is a compile-time constant. The sizeof operator takes one of the following forms: sizeof 操作符的作用是返回一个对象或类型名的长度,返回值的类型为 size_t(第 3.5.2 节),长度的单位是字节(第 2.1 节)。size_t 表达式的结果是编译时常量,该操作符有以下三种语法形式: sizeof (type name); sizeof (expr); sizeof expr; Applying sizeof to an expr returns the size of the result type of that expression: 将 sizeof 应用在表达式 expr 上,将获得该表达式的结果的类型长度: Sales_item item, *p; // three ways to obtain size required to hold an object of type Sales_item sizeof(Sales_item); // size required to hold an object of type Sales_item sizeof item; // size of item's type, e.g., sizeof(Sales_item) sizeof *p; // size of type to which p points, e.g., sizeof(Sales_item) Evaluating sizeof expr does not evaluate the expression. In particular, in sizeof *p, the pointer p may hold an invalid address, because p is not dereferenced. 将 sizeof 用于 expr 时,并没有计算表达式 expr 的值。特别是在 sizeof *p 中,指针 p 可以持有一个无效地址,因为不需要对 p 做解引用操作。 The result of applying sizeof depends in part on the type involved: 使用 sizeof 的结果部分地依赖所涉及的类型:
Because sizeof returns the size of the entire array, we can determine the number of elements by dividing the sizeof the array by the sizeof an element: 因为 sizeof 返回整个数组在内存中的存储长度,所以用 sizeof 数组的结果除以 sizeof 其元素类型的结果,即可求出数组元素的个数: // sizeof(ia)/sizeof(*ia) returns the number of elements in ia int sz = sizeof(ia)/sizeof(*ia); |