Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use sizeof for class members

Shulou Source: shulou.com Published: 2022-06-01 19:48:15 10月06日 Update

This article mainly explains "how to use sizeof for class members". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use sizeof for class members.

Sizeof operator

The sizeof operator returns the number of bytes of memory occupied by an expression or type. It returns a constant expression of type size_t.

Suppose you have the following structure:

Struct Point3d {int x; int y; int z;}

You can initialize it like this:

Point3d pt; memset (& pt, 0, sizeof (pt))

You can also initialize it like this:

Point3d pt1; memset (& pt1, 0, sizeof (Point3d))

You can also initialize in batches:

Point3d ptarray; memset (ptarray, 0, sizeof (ptarray))

Many processes related to memory operations need to know the amount of memory space occupied by data or types. You can use the sizeof operator at this point. The object calculated by sizeof can be either a data or a type.

It is important to note that if the object of the operation is a pointer, then you can only get the size of the pointer itself rather than the size of the pointer pointing to the data. For example, the following code cannot initialize all x array elements.

Int x [10]; int * p = x; memset (p, 0, sizeof (p) / sizeof (* p))

Sizeof in C++

Suppose there are the following structures:

Struct Image {int width; int height; char data [10000];}

You can initialize data members like this:

Image image1; memset (image1.data, 0, sizeof (iamge1.data))

After Category 11, you can also initialize it like this:

Image image1

Memset (image1.data, 0, sizeof (Image::data))

Note that the parameters of sizeof can directly use the scope operator to obtain the size of the member without passing through the object.

Quiz

Is there a problem with the following code?

Int data [100]; constexpr size_t cnt = sizeof (data) / sizeof (* data); int info [cnt * 2]; msmet (info, 0, sizeof (info)); Thank you for reading, the above is the content of "how to use sizeof for class members". After the study of this article, I believe you have a deeper understanding of how to use sizeof for class members, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Members operations sizes types operators memory objects pointers data facets learning code content space structures expressions problems actions elements parameters Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Huawei MySQL Redmi NVidia