A summary of the sizeof problem in C + + interview

Source: Internet
Author: User

Original: Http://blog.sina.com.cn/s/blog_7c983ca60100yfdv.html#SinaEditor_Temp_FontName

(1) sizeof is an operator, not a function.

MSDN: Thesizeof keyword gives the amount of storage, in bytes, associate with a variable or a type (including aggregate Types). This keyword returns a value of type size_t (typedef unsigned int size_t).

Syntax:sizeof (object);=> sizeof (1);  sizeof (typename); =>sizeof (int); sizeof object;=>sizeof 1; (Note that sizeof TypeName is wrong)

(2) sizeof cannot be obtained void the length of the type.

You cannot use sizeof (void); This will produce:error c2070:illegal sizeof operand

For example, the following code:

void Fun () {

}

int main () {

Cout<<sizeof (Fun ()) <<endl;

return 0;

}//This compilation is not going to pass.

Char Fun () {

Return ' a ';

}

int main ()

{

Cout<<sizeof (Fun ()) <<endl;

return 0;

}//extension, this is the length of the measured return value, so it is 1, not the length of the pointer 4. Combined with the 8th view.

(3)         sizeof can be obtained void The length of the pointer of type .

The

Currently basically all compilers regard the pointer size as 4byte. The pointer is also a variable, but this variable is very special, it is the address of other variables to store the variable. As a result of the current 4gb, the minimum addressable unit is Span lang= "en-us" xml:lang= "en-US" >byte,4gb equals 232byte. So much memory from the address how to encode, only need to use 32 bit on the line, and 32bit=32, 8=4byte, meaning as long as 4byte can store these memory addresses. Therefore, any type of pointer variable is sizeof operation, the result is 4. ( One question, pointer type with 4byte stores only the address that the pointer points to, How do you tell what kind of pointer it is? )

(4) sizeof The length of the array that can be evaluated for statically allocated memory.

int a[10];sizeof (a); So the length is 10*4=40. ( extended question: The difference between an array name and a pointer.) See the next article ), in addition note char ch[]= "abc"; sizeof (CH), the result is 4, note that the string array at the end of the ' + ', usually we can use sizeof to calculate the number of elements contained in the array. The practice is:int n=sizeof (a)/sizeof (a[0]);

It is important to note that sizeof is used for the shape parameter group of a function . such as:

void fun (int arr[10]) {

int n = sizeof (arr);

The value of}//n is 4

The reason for this is that when the function parameter is passed, the array is converted to a pointer. By adding a direct pass through the array, the copy of the array element (the actual parameter to the copy of the parameter) must be involved, which results in very inefficient execution when the array is very large! Instead of just passing the address of the array (that is, the pointer), you only need to copy 4Byte.

Extension: sizeof and the strlen The difference:

The strlen (char*) function is the actual length of the string, it is the method of the first encounter from the beginning, if you only define the initial value is not assigned to it, the result is uncertain, it from the pointer to the first address has been looking down until the encounter '.

Char Aa[10];strlen (AA);      The result is a variable sizeof (AA); The result is ten

Char aa[10]={'};strlen ' (AA);      The result is 0 sizeof (AA); The result is ten

Char aa[]= "LRP"; strlen (AA);      The result is 3 sizeof (AA); The result is 4 .

Char*aa= "0123456789"; Case of a string constant

sizeof (AA); The result is 4, the length of the pointer

sizeof (*AA); The result is 1, the space of the first character

strlen (AA); The result is 0, the length of the string

Char aaa[]={"LRPLRP"};

int A, B;

Fun (AAA,A,B);

void Fun (char aaa[],int&a,int&b)

{

A=strlen (AAA);

B=sizeof (AAA);

}

Get the a=6,b=4. Inside the function, although AAA is converted to a pointer, the strlen tests the length of the string until the AAA starts , and sizeof is the length of the measured pointer.

(5) sizeof cannot calculate the size of dynamically allocated memory

For example int*a = new INT[10]; int n = sizeof (a); the value of n is 4.

(6) sizeof cannot find the length of an array that is not completed

Suppose there are two source files:file1.cpp and file2.cpp, where file1.cpp is defined:

int arraya[10]={1,2,3,4,5,6,7,8,9,10};

int arrayb[10]={11,12,13,14,15,16,17,18,19,20};

The file2.cpp contains the following statements:extern arraya[]; extern arrayb[10];

Cout<<sizeof (Arraya) <<endl; Compilation error

Cout<<sizeof (Arrayb) <<endl;

The third statement in file1.cpp was compiled with an error, and the fourth statement was correct. Reason: sizeof (arraya) attempts to find the size of an incomplete array. The incomplete array here is an array of exponential group sizes that are not determined. sizeof operator is to find the size of an object, but the declaration: extern int Arraya[] Just tells the compiler arraya is an integer array, but does not tell the compiler how many elements it contains, so for file2.cpp sizeof that it could not find Arraya size, so the compiler simply does not let you compile through. arrayb explicitly told arrayb is a 10 elements of an integer array, so the big thing is OK.

(7) When An expression is an operand of sizeof, it returns the evaluated type size of the expression, but it does not evaluate an expression. (This is important)

Char ch=1;

int num=1;

int n1=sizeof (ch+num); Result n1=4

int n2=sizeof (ch=ch+num); N2=1,ch=1

Because of the default type conversion reason, thech+num evaluates to an int, so the value of N1 is 4. The type of the result of the expression ch=ch+num is char, remembering that while the ch+num is calculated , the result is int, but when the result is assigned to CH, the type conversion is made, so the final type of the expression is char, so n2 equals 1.

ForN2=sizeof (Ch=ch+num); At first glance, the program seems to have achievedch plus num and assigned to ch function, this is not the case, because sizeof The is only concerned with type size, so it naturally should not evaluate an expression . However, int len=3; cout<<sizeof (Int[++len]) << "," <<len; the answer to the output is Span lang= "en-us" xml:lang= "en-US" >16,4. (the author says in the original dev C + + compiler, but after VC under test, compilation does not pass. Later changed to int num = 3;      int aaa[]={1,2,3,4,5,6};  cout<<sizeof (Aaa[++num]) << "," <<num<<endl; output is 4,3. thus ++num operation is not performed), so try not to sizeof directly to the expression size, in order to avoid errors.

(8) sizeof a function call can be sized, and the size obtained is equal to the size of the function return type, but the function body is not executed.

int fun (int &num)

{

int A, B;

A = 10;

b = 2;

num = A/b;

return num;

}

int main ()

{

int num = 0;

Cout<<sizeof (num) <<endl;

cout<<num<<endl;

return 0;

}//output Results 4 0

sizeof (num) is the size of the function return type, and fun ( NUM) is a return value type of int, so the equivalent of sizeof (int) results in Span lang= "en-us" xml:lang= "en-us" >4. Also do not consider this length as the size of the space occupied by local variables within the fun functions (the result is considered Span lang= "en-us" xml:lang= "en-us" >8, i.e. a and B two int length is also wrong) Also note that sizeof (Fun (num)) It is not the size of the function pointer, Remember to find the length size of the return value type .

This is similar to feature 7. sizeof's operand is a function call, and it does not execute the function body. For this reason, we recommend that you do not put the function body in parentheses behind the sizeof, so that people mistakenly think that the function body executed, in fact, it did not execute at all. In addition, we can not use sizeof to calculate the size of a function that returns a void , such as 2 to compile an error.

Also note the size of the sizeof (fun) is how much? In fact, the answer is not, because the compilation does not pass. (Many people may think that fun is the function name, and then the function name is equivalent to the address of the function, the address is a pointer), and then got its value is 4. But that's not the case, but it's not compiled.

(9) sizeof the size of the struct (and its objects) is not equal to the size of each data member object.

The size of the

struct is closely related to the members of the struct, not simply the sum of the size of each member. For example, two structural bodies aa and bb. , using sizeof respectively results are 24 and 16. You can see sizeof (AA) does not equal sizeof (int) +sizeof (double) +sizeof (int)

struct aa{

        int AA;

       double BB;

       int cc;

};

struct bb{

       int AA;

       int BB;

       double cc;

};

Struct Member Alignment rules: (1) The structure size equals the integer multiples of the maximum member size in the structure body, and (2) the first address of the member in the structure is offset from the first address of the struct as an integer multiple of its type size, for example The offset of a double member relative to the first address of the struct should be an integer multiple of 8, (3) to satisfy Rule 1 and rule 2 the compiler will then make a byte fill after the struct member.

At design time, the group number carefully arranges the order of the individual members in the structure.

(Ten) sizeof cannot be used to calculate the size of a struct's bit-field members, but it can be obtained by the size of the struct that contains the bit-field members.

Bit field: The size of a type is in bytes (byte) as thebasic unit, such as sizeof (char) is 1byte. But the bool type value only true and false, is supposed to use only 1bit is enough, but in fact sizeof (bool) equals 1. To provide a mechanism for calculating the storage space of variables, this is the bit field. In a nutshell, a colon + an integer followed by a struct member variable represents a bit field, so look closely at the following structure:

struct a{

BOOL B:1;

Char Ch1:4;

Char Ch2:4;

}item;

The struct attempts to use a variable B of type bool to occupy only 1 bits, allowing ch1 and CH2 to occupy only 4 bits, respectively, to achieve the function of memory budgeting. Statements like sizeof (item.b) and sizeof (ITEM.CH1) for the size of a bit-field member cannot be compiled. The reason:sizeof Returns the size of the operand in bytes.

A struct that contains bit fields can be sized with sizeof, but its evaluation rules are complex, do not involve member alignment, and are related to the collective compilation environment.

Extension: The result of Classa{};sizeof (A) is 1, the reason: class instantiation is to allocate a block of address in class memory, each instance in memory has a unique address, the same empty class will be instantiated, so the compiler will give an empty class implicitly add a Byte, This allows an empty class to be instantiated with a unique address. So its length is 1. (the compiler adds a char type to the class in order to distinguish between different classes, and if there are 256 empty classes in a file that are larger than the range represented by the char type, you cannot distinguish between empty classes)

A summary of the sizeof problem in C + + interview

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.