iOS Development Series--c language construction type

Source: Internet
Author: User

Overview

In the first section we refer to the C language construction type, divided into: array, struct, enumeration, common, of course, the contents of the preceding array has been said a lot, this section will focus on the other three types.

    1. Structural body
    2. Enumeration
    3. Shared body
Structural body

The array is stored in a series of identical data types, so if you want a variable to store different data types using structs, struct definitions are similar to those in high-level languages such as C + +, C #, and Java, but in fact they are very much different. A struct is a type, not a variable, except that this type can be composed of other C-language basic types.

////main.c//constructedtype////Created by Kenshin Cui on 14-7-18.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#include<stdio.h>//struct type datestructdate{intYear ; intmonth; intDay ;};structperson{Char*name; intAge ; structDate birthday;//One struct uses another struct type, struct-type variable declaration must be preceded by the structure keywordfloatheight;};intMain (intargc,const Char* argv[]) {    structPerson p={"Kenshin", 28,{1986,8,8},1.72}; //define struct variable and initialize it, do not allow to define reinitialization first, for example: struct person p;p={"Kenshin", 28,{1986,8,8},1.72};printf ("name=%s,age=%d,birthday=%d-%d-%d,height=%.2f\n", P.name,p.age,p.birthday.year,p.birthday.month,p.birthday.day,p.height); //Result: name=kenshin,age=28,birthday=1986-8-8,height=1.72, struct reference is through "struct variable. Member name"printf ("Len (Date) =%lu,len (person) =%lu\n",sizeof(structDate),sizeof(structPerson )); //Result: Len (Date) =12,len (person) =32return0;}

For the above example, you need to make the following statement:

    1. struct variables can be declared at the same time as the struct type is defined;
    2. If the struct type is defined at the same time as the struct variable is declared, the structure name can be omitted;
    3. Defining struct types does not allocate memory, and memory allocations (similar to basic types) are made when defining struct-body variables;
    4. The amount of memory occupied by the struct type is equal to the sum of the memory size of all members (if memory alignment is not considered);

The 4th need to be explained, such as the above code is the result of running under the 64-bit compiler (int length 4,char length 1,float type 4), date=4+4+4=12. But the person is not as simple as the normal way to calculate the person=8+4+12+4=28, but the result from the above code is 32, why? Here we have to introduce a concept of "memory alignment", the concept of memory alignment is not detailed here, you need to understand is: in Mac OS x alignment parameters default to 8 (you can add #pragma pack (8) in the code to change the alignment parameters), if the structure of the type is not greater than 8, The length of the struct is the sum of its member types, but if the length of the member variable is greater than the alignment parameter, the resulting result is not necessarily the sum of the individual member variables. The length of the person type is 32, but the main reason is that because the date type length 12 is stored with an offset of 12 that is not a multiple of 8, the reason for the memory alignment is to add 4 completion lengths, which are listed in tabular form:

For the specific source of the form, please watch the video below (note that the reason for recording the software is unclear for the first few seconds but does not affect the analysis):

Next, look at the structure array, pointers to the struct body:

////main.c//constructedtype////Created by Kenshin Cui on 14-7-18.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#include<stdio.h>structdate{intYear ; intmonth; intDay ;};structperson{Char*name; intAge ; structDate birthday; floatheight;};voidChangeValue (structPerson person ) {person.height=1.80;}intMain (intargc,const Char* argv[]) {    structPerson persons[]={{"Kenshin", 28,{1986,8,8},1.72}, {"Kaoru", 27,{1987,8,8},1.60}, {"Rosa", 29,{1985,8,8},1.60}};  for(inti=0, i<3; ++i) {printf ("name=%s,age=%d,birthday=%d-%d-%d,height=%.2f\n", Persons[i].name, Persons[i].age, Persons[i].birthday.year, p    Ersons[i].birthday.month, Persons[i].birthday.day, persons[i].height); }    /* Output result: name=kenshin,age=28,birthday=1986-8-8,height=1.72 name=kaoru,age=27,birthday=1987-8-8,height=1.60 name=rosa,age=29,birthday=1985-8-8,height=1.60 * *structPerson Person=persons[0];    ChangeValue (person); printf ("name=%s,age=%d,birthday=%d-%d-%d,height=%.2f\n", Persons[0].name, Persons[0].age, Persons[0].birthday.year, PERSONS[0].BIRTHD    Ay.month, Persons[0].birthday.day, persons[0].height); /* Output Result: name=kenshin,age=28,birthday=1986-8-8,height=1.72 */structPerson *p=&person; printf ("name=%s,age=%d,birthday=%d-%d-%d,height=%.2f\n", (*p). Name, (*p). Age, (*p). Birthday.year, (*p). Birthday.month, (*p)    . Birthday.day, (*p). height); /* Output Result: name=kenshin,age=28,birthday=1986-8-8,height=1.72 */printf ("name=%s,age=%d,birthday=%d-%d-%d,height=%.2f\n", P->name, P->age, P->birthday.year, P->birthday.month,    P->birthday.day, P->height); /* Output Result: name=kenshin,age=28,birthday=1986-8-8,height=1.72 */return0;}

A struct is passed as a function parameter that is the value of a member (value passing instead of a reference pass), which can be accessed through the "-to" operator for a struct pointer.

Enumeration

Enumeration types are a simple type of data, and in fact, in C, enumerated types are handled as shaping constants, often referred to as "enumeration constants."

////main.c//constructedtype////Created by Kenshin Cui on 14-7-18.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#include<stdio.h>enumseason{//spring=0,summer=1,autumn=2,winter=3 by defaultspring, summer, autumn, winter};intMain (intargc,const Char* argv[]) {    enumSeason Season=summer;//enumeration assignment, equivalent to Season=1printf ("summer=%d\n", season); //Result: Summer=1 for(Season=spring;season<=winter;++season) {printf ("Element value=%d\n", season); }    /* Results: Element value=0 element value=1 element value=2 element value=3 */return0;}

It is important to note that the default value of the enumeration member starts at 0, and if one of the members is assigned a value, the other subsequent members are assigned a value, for example, if summer is manually specified as 8, then autumn=9,winter=10, and Sprint is 0.

Shared body

The common body is also called union because its keyword is union (which seems to be used frequently by database operations), it is not used as frequently as enumerations and structs, but as a data type in C we also need to understand its usage. From the previous analysis we know that the total length of the struct equals the sum of all the members (and of course the alignment problem may also be encountered at this time), but unlike the struct, all members of the common body share a piece of memory, the order starts from the low address, only one of the members can be used at a time, and the final size of the Union , assigning a value to a member may overwrite another member.

////main.c//constructedtype////Created by Kenshin Cui on 14-7-20.//Copyright (c) 2014 Kenshin Cui. All Rights reserved.//#include<stdio.h>Uniontype{CharA; Short intb; intc;};intMain (intargc,const Char* argv[]) {    UnionType t; T.a=' A ';    t.b=10;        t.c=65796; printf ("Address (Type) =%x,address (T.A) =%x,address (t.b) =%x,address (t.c) =%x\n", &t,&t.a,&t.b,&t.c); //Result: Address (Type) =5fbff7b8,address (T.A) =5fbff7b8,address (t.b) =5fbff7b8,address (t.c) =5fbff7b8printf ("Len (Type) =%d\n",sizeof(UnionType)); //Result: Len (Type) =4printf ("t.a=%d,t.b=%d,t.c=%d\n", t.a,t.b,t.c); //Result: t.a=4,t.b=260,t.c=65796return0;}

Here it is important to explain a question: Why T.a, t.b, t.c output results are 4, 260, 65796, of course t.c equals 65796 is not strange, but t.a front assignment is ' a ' should not be 97, and t.b should not be 10? In fact, it is clear that the concept of the common body of the problem should be clarified.

According to the aforementioned, the common body can only use one of the members at a time, for the above code after three times the assignment is actually t.c, and through the above output we do see that C is valid. A common feature is that its members are stored in the same area of memory, and the size of the area needs to be determined by the length of the member's largest length of the member. Because the above code is compiled under the 64-bit compiler, the specific length: Char=1,short int=2,int=4, so that the length of the type is 4, and according to the output address above, you can get the following storage information (note the storage of the data: High address storage, Low address storage status):

When reading C, its binary is "00000000 00000001 00000001 00000100", converted to decimal is 65796, and after three assignments, this time B's storage has been the C member's low data coverage, B is the length of two, So the binary data obtained from the starting address of two bytes is "00000001 00000100" (b The original data has been overwritten by C low 2-bit data, in fact, this is the low 2-bit data of C), converted to decimal is 260; A similar data at this point is the lower one of C. 00000100 ", converted to decimal is 4.

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.