Team LiB
Previous Section Next Section

5.8. The sizeof Operator

5.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 的结果部分地依赖所涉及的类型:

  • sizeof char or an expression of type char is guaranteed to be 1

    char 类型或值为 char 类型的表达式做 sizeof 操作保证得 1。

  • sizeof a reference type returns the size of the memory necessary to contain an object of the referenced type

    对引用类型做 sizeof 操作将返回存放此引用类型对象所需的内在空间大小。

  • sizeof a pointer returns the size needed hold a pointer; to obtain the size of the object to which the pointer points, the pointer must be dereferenced

    对指针做 sizeof 操作将返回存放指针所需的内在大小;注意,如果要获取该指针所指向对象的大小,则必须对指针进行引用。

  • sizeof an array is equivalent to taking the sizeof the element type times the number of elements in the array

    对数组做 sizeof 操作等效于将对其元素类型做 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);

Exercises Section 5.8

Exercise 5.22:

Write a program to print the size of each of the built-in types.

编写程序输出的每种内置类型的长度。

Exercise 5.23:

Predict the output of the following program and explain your reasoning. Now run the program. Is the output what you expected? If not, figure out why.

预测下列程序的输出是,并解释你的理由。然后运行该程序,输出的结果和你的预测的一样吗?如果不一样,为什么?

     int x[10];   int *p = x;
     cout << sizeof(x)/sizeof(*x) << endl;
     cout << sizeof(p)/sizeof(*p) << endl;

Team LiB
Previous Section Next Section