sizeof operator
The sizeof operator returns the number of bytes of memory space occupied by an expression or type. It returns a constant expression of type size_t.
Suppose you have the following structure:
structPoint3d{
int x ;
int y ;
int z ;
};
It can be initialized like this:
Point3d pt;
memset(&pt,0,sizeof(pt));
It can also be initialized like this:
Point3d pt1;
memset(&pt1,0,sizeof(Point3d));
Batch initialization is also possible:
Point3d ptarray[100];
memset(ptarray,0,sizeof(ptarray));
Many processes related to memory operations need to know how much memory space the data or type occupies. This is where the sizeof operator can be used. The object calculated by sizeof can be data or type.
One thing to note is 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 data pointed to by the pointer. For example the following code fails to initialize all x array elements.
int x [ 10 ];
int *p = x;
memset(p,0,sizeof(p)/sizeof(*p));
sizeof in C++
Suppose you have the following structure:
structImage{
intwidth;
intheight;
char data [ 10000 ];
};
The data member can be initialized like this:
Image image1;
memset(image1.data,0,sizeof(iamge1.data));
After C++11, you can also initialize like this:
Image image1;
memset(image1.data,0,sizeof(Image::data));
Pay attention to the parameter of sizeof, you can directly use the scope operator to get the size of the member without passing the object.
Quiz
Is there something wrong with the code below?
int data[100];
constexpr size_t cnt = sizeof(data)/sizeof(*data);
int info[cnt * 2];
memset(info, 0, sizeof(info));
作者观点
聚沙成塔,集腋成裘。一点一滴的变化,使C++变得越来越好用。