For faster navigation, this Iframe is preloading the Wikiwand page for Sizeof.

Sizeof

sizeof是编程语言C语言C++中的操作符。它能表示資料類型或對象的存储大小(內存字節數)[1],存储大小以一個char大小的单位來衡量。因此sizeof (char)等於1 。被計算的数据类型不仅可以是原始型別,例如整数浮点类型,还可以是指针类型和复合数据类型(联合体结构体和 C++)。

语法

[编辑]

sizeof返回的是size_t数据类型。对于变量作为运算数,可以不加括号;对于数据类型作为运算数,必须加括号。例如:

char c;
printf ("%zu,%zu\n", sizeof c, sizeof (int));

C++11使用该运算符返回可变参数模板的参数个数:

template <typename... Args>
std::size_t GetSize (Args&&... args)
{
    /* Get size of parameter pack.*/
    std::size_t Count= sizeof... (args);
    return Count;           
}

C99支持结构的“可灵活数组”(flexible array)成员:返回結構中包含padding,但不包括“可灵活数组”的佔用空間,此時的功能如同 offsetof(flexarray, array)

#include <stdio.h>

struct flexarray {
    char val;
    int array[];  /* Flexible array member; must be last element of struct */
};

int main(int argc, char **argv)
{
    printf("sizeof (struct flexarray) == %zu\n", sizeof (struct flexarray)); //通常结果为:sizeof (struct flexarray) == 4
    return 0;
}

C99还支持动态长度数组,其长度在运行时确定:

#include <stddef.h>

size_t flexsize(int n)
{
   char b[n + 3];   /* Variable length array */
   return sizeof b;  /* Execution time sizeof */
}

int main(void)
{
  size_t size = flexsize(10); /* flexsize returns 13 */
  return 0;
}

C++11支持获取类的成员的尺寸,不必实例化出对象:

#include <iostream>

struct foo {
  int a;
  int b;
};

int main ()
{
  std::cout << sizeof foo::a << "\n" << sizeof (foo) << "\n";
}

参考文献

[编辑]
{{bottomLinkPreText}} {{bottomLinkText}}
Sizeof
Listen to this article

This browser is not supported by Wikiwand :(
Wikiwand requires a browser with modern capabilities in order to provide you with the best reading experience.
Please download and use one of the following browsers:

This article was just edited, click to reload
This article has been deleted on Wikipedia (Why?)

Back to homepage

Please click Add in the dialog above
Please click Allow in the top-left corner,
then click Install Now in the dialog
Please click Open in the download dialog,
then click Install
Please click the "Downloads" icon in the Safari toolbar, open the first download in the list,
then click Install
{{::$root.activation.text}}

Install Wikiwand

Install on Chrome Install on Firefox
Don't forget to rate us

Tell your friends about Wikiwand!

Gmail Facebook Twitter Link

Enjoying Wikiwand?

Tell your friends and spread the love:
Share on Gmail Share on Facebook Share on Twitter Share on Buffer

Our magic isn't perfect

You can help our automatic cover photo selection by reporting an unsuitable photo.

This photo is visually disturbing This photo is not a good choice

Thank you for helping!


Your input will affect cover photo selection, along with input from other users.

X

Get ready for Wikiwand 2.0 🎉! the new version arrives on September 1st! Don't want to wait?