C language Structure (struct) common use method __c language

Source: Internet
Author: User

Review the struct today and dig up the little details that you didn't notice before:


Basic definition: Structure, popular speaking is like packaging packaging, some of the common characteristics (such as the attributes belonging to a certain kind of things, often a business-related attribute of aggregation) of variables encapsulated in the internal, through a certain method access to modify internal variables.



structure Body Definition:


The first: Only the definition of the struct body

struct stuff{
        char job[20];
        int age;
        float height;
};


Second : the structural body definition of the initialization of the "struct variable" attached to the struct type

Directly with variable name Huqinwei
struct stuff{
        char job[20];
        int age;
        float height;
} Huqinwei;

Perhaps the initial look is not accustomed to easily confused, in fact, this is equivalent to:

struct stuff{
        char job[20];
        int age;
        float height;
};
struct Stuff Huqinwei;

Third: If the structure you use only a variable Huqinwei, and no longer need to use

struct Stuff yourname;
To define a second variable.

The structural body definition of an additional variable initialization can further simplify the third type :

struct{
        Char job[20];
        int age;
        float height;
} Huqinwei;
Removing the name of the structure is more concise, but it's not possible to define other variables with the same structure--at least I don't know how to do it now.

Definition and access of structure variables and their internal member variables:

Let's go around the mouth. The concepts of structural variables and internal member variables of structures should be distinguished.


As the second mentioned earlier, the declaration of a struct variable can be used:

struct Stuff yourname;
The definition of its member variable can be carried out with the declaration:

   struct Stuff Huqinwei = {"Manager", 30,185};

You can also consider the assignment between the struct bodies:

        struct Stuff faker = Huqinwei;
or    struct stuff faker2;      faker2 = faker;
Print, each member variable of the visible structure is exactly the same

If you do not use the top two methods, then the operation of the member array will be slightly troublesome (the for loop may be better)

        Huqinwei.job[0] = ' M ';
        HUQINWEI.JOB[1] = ' a ';
        Huqinwei.age =;
       Huqinwei.height = 185;

The access to struct member variables can be accessed in addition to the symbol ".", which is also accessible by "->" (below).



References (c + +), pointers, and arrays:

The first is the references and pointers:

int main ()
{
        struct stuff Huqinwei;

        struct stuff &ref = Huqinwei;
        Ref.age = m;
        printf ("Huqinwei.age is%d\n", huqinwei.age);
        printf ("Ref.age is%d\n", ref.age);

        struct Stuff *ptr = &Huqinwei;
        Ptr->age =;
        printf ("Huqinwei.age is%d\n", huqinwei.age);
        printf ("Ptr->age is%d\n", huqinwei.age);
Now that you've written it, add the reference to the pointer
        struct stuff *&reftoptr = ptr;
        Reftoptr->age =;
        printf ("Huqinwei.age is%d\n", huqinwei.age);
        printf ("Reftoptr->age is%d\n", reftoptr->age);


}


Correction: The initialization statement that was previously given to the reference was incorrectly written, and no reference was made to something that was not in pure C (in a blog such as C).

Reference is a unique mechanism of C + +, must rely on the compiler support, as to the reference conversion to C in essence, I have a post wrote


Structs cannot be exception, they must have arrays:

struct test{
        int a[3];
        int b;
};
For situations where arrays and variables exist at the same time, there are the following definition methods:
struct test student[3] =      {{66,77,55},0},
{{44,65,33},0},
{{46,99,77},0}}};
Special, can be reduced to:       struct test student[3] =       {{66,77,55,0},
                                        {44,65,33,0},
                                        {46,99,77,0}};


variable-length structural body

An array that can become longer

#include <stdio.h>
#include <malloc.h>
#include <string.h>
typedef struct changeable{
        int icnt;
        Char pc[0];
} schangeable;

Main () {
        printf ("size of struct changeable:%d\n", sizeof (schangeable));

        Schangeable *pchangeable = (schangeable *) malloc (sizeof (schangeable) + 10*sizeof (char));
        printf ("Size of pchangeable:%d\n", sizeof (pchangeable));

        Schangeable *pchangeable2 = (schangeable *) malloc (sizeof (schangeable) + 20*sizeof (char));
        pchangeable2->icnt =;
        printf ("Pchangeable2->icnt:%d\n", pchangeable2->icnt);
        strncpy (pchangeable2->pc, "Hello World", one);
        printf ("%s\n", pchangeable2->pc);
        printf ("Size of Pchangeable2:%d\n", sizeof (Pchangeable2));
}

Run results

Size of struct changeable:4
size of pchangeable:4
pchangeable2->icnt:20
Hello World
size of Pchan Geable2:4

The length of the structure itself is an int length (this int is usually only meant to represent the length of the array behind), and the length of the array behind is not counted, but the array can be used directly.

(There's a pointer behind that.) The pointer also takes up the length. This is not accounted for. The principle is very simple, this thing is completely the tail of the array, malloc open up a continuous space. In fact, this should not be a mechanism, the feeling should be more like a skill bar.


20160405 Supplements:

An inelastic array cannot define an elastic (flexible) variable in the form of "Char a[]" and must be a definite size.

The elastic array is in the structure, and the following form is the only one allowed:

struct s
{
        int A;
        Char b[];

An inverted order will let B and a data overlap and will not pass at compile time.

Char b[] = "hell"; not both (c and C + +)
The less integral variable A also makes the entire structure length 0,compiler not allow compilation to pass. The difference is, in fact, C + + form is to allow the empty structure, essentially through the mechanism to avoid the pure empty structure and class objects, automatic allocation of empty structure objects a byte (sizeof () return 1) to facilitate the separation of objects, avoid address overlap. So, C. If there is an empty structure, define two (or a dozen, or simply an array) of variables (objects) of the struct, and the address is exactly the same. debugging to see the program run, these statements are actually when fart put, there is no running, no practical significance, C does not support the empty structure of this kind of thing (or I also did not think good what occasion useful)

struct S2
{
//      char a[]  = "HASD";      int c;
};
int main ()
{
        struct s2 s22;
        struct S2 s23;
        struct S2 S24;
        struct s2 s25;
}

The exception is that C + + does not allocate space to a structure with an elastic array (may fear some kind of conflict with the variable-length structural mechanism, such as the size):

struct S
{
        char b[];

struct S
{
//        char b[];
};
C + + is not the same, empty structure instead of "big" (sizeof () return 1)

20160321 Supplement: This mechanism utilizes a very important feature-the difference between arrays and pointers. Arrays and pointers are the same in many operations, but they are different in nature. Most intuitively, the pointer can be changed to point to, the array cannot, because each memory address occupied by the array is used to hold the variable or object, and the memory address occupied by the pointer holds an address, and the array does not hold a single structure that points to the address. The position of the array is fixed, just as the position of the pointer variable itself is fixed, the value of the pointer is changed to the target address, and because the array does not store the destination address, it does not change the point. An attempt to assign an address to an array is only to say that the pointer is assigned to an array and the type is incompatible.




Structure Nesting:

Structure nesting in fact, not too unexpected things, as long as the following a certain law can:

For "opportunistic One", only interested in the final structure variables, where A, B can also be deleted, but preferably with
struct a{ 
        struct b{
             int c;
        }
        b;
}
A;
Access is as follows:
A.B.C = 10; 
In particular, you can define structure B on one side and use it on the other:

struct a{
        struct b{
                int c;
        } b;

        struct B sb;

} A
How to use and test:

        A.B.C = one;
        printf ("%d\n", A.B.C);
        A.SB.C =;
        printf ("%d\n", A.SB.C);


However, if the nested structure B is declared within a, and no corresponding object entity B is defined, the size of the struct B is not counted into the struct a.


Structure Body and function:

For reference, first:

void func (int);
Func (A.B.C);
Using an INT member variable in a struct as something like a normal int variable is a way of thinking without thinking.

The other two are the transfer of copies and pointers:

struct a defines IBID.
//sets two functions, passing struct a structure and its pointers, respectively.
void func1 (struct a) {
printf ("%d\n", A.B.C);
}
void Func2 (struct * A) {
printf ("%d\n", A->B.C);
}
Main () {
A.B.C = 112;
struct A * PA;
PA = &a;
Func1 (a);
Func2 (&a);
FUNC2 (PA);



occupy memory space:

The struct structure is not able to request memory space when the structure is defined, but if it is a struct variable , it can be allocated when it is declared--the relationship is like a C + + class and object, and the object allocates memory (though, strictly speaking, as a code snippet, The structure Definition section ". Text" really does not occupy space. Of course, this is another topic of the category.


The size of the structure is usually (but usually) the sum of the variables contained in the structure, and the following prints out the size of the structure:

        printf ("Size of struct man:%d\n", sizeof (struct man));
        printf ("size:%d\n", sizeof (Huqinwei));


The bottom is not usually:

For the smaller members of the structure, it is possible to be forcibly aligned, resulting in space vacancy, which is related to the mechanism for reading memory, for efficiency. Typically 32-bit machines are aligned in 4 bytes, less than all when 4 bytes, there is a continuous less than 4 bytes, you can not be anxious to align, wait until the whole, plus the next element beyond a alignment position, before starting to adjust, such as 3+2 or 1+4, the latter need to be another (the bottom of the structure is 8bytes), There are a number of related examples, not to repeat.

struct S
{
char A;
Short B;
int c;
}
Accordingly, the 64-bit machine is aligned by 8 bytes. However, alignment is not absolute, with the #pragma pack () You can modify the alignment if by changing to 1, the size of the structure is the sum of the actual size of the member variable.


Unlike C + + classes, a struct can not initialize an internal variable of a struct.

as follows, the error is demonstrated:

#include <stdio.h>
//Direct with variable name Huqinwei
struct stuff{
//      char job[20] = "programmer";      Char job[];      int age =;      float height = 185;
} Huqinwei;



PS: The declaration of the structure should also pay attention to the location, the scope is not the same.

C + + structure variable declaration definition and C is slightly different, plainly is more "object-oriented" style, lower requirements.


So familiar with the common methods, should pay attention to what often make mistakes, see C language structure common mistakes.



Related Article

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.