Common usage of C language constructs (struct) (details)

  • 2020-05-12 03:00:46
  • OfStack

Basic definition: structure, commonly known as packaging and encapsulation, encapsulates some variables that have common characteristics (such as the attributes belonging to a certain type of things, which are often the aggregation of some business-related attributes) inside, and accesses and modifies the internal variables through a definite method.

Structure definition:

Type 1: only struct definitions


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

Type 2: an initialized struct definition with "struct variables" attached to the struct type


// Take the variable name directly Huqinwei 
struct stuff{ 
    char job[20]; 
    int age; 
    float height; 
}Huqinwei; 

Maybe it's easy to get confused when you're not used to it at first. In fact, it's equivalent to:


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

Type 3: if you only use one variable for the structure, Huqinwei, you no longer need to use it


struct stuff yourname; 

To define the second variable.

Then, the structure definition initialized by additional variables can also be simplified by 1 step out of the third:


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

Remove the struct name to make it simpler, but you won't be able to define other struct variables either -- at least I don't know how to do that right now.

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

Around the mouth? Distinguish between struct variables and the concept of struct internal member variables.

As mentioned in category 2, struct variables can be declared by:


struct stuff yourname; 

Its member variables can be defined as follows:


struct stuff Huqinwei = {"manager",30,185}; 
 You can also consider the assignment between structures: 
[cpp] view plain copy  in CODE View the code snippet on derived to my code snippet 
    struct stuff faker = Huqinwei; 
// or   struct stuff faker2; 
//   faker2 = faker; 

Print, see the structure of each 1 member of the variable 1 module 1

If you do not use the above two methods, then the operation of the member array is a little bit troublesome (for loop is probably better)


Huqinwei.job[0] = 'M'; 
Huqinwei.job[1] = 'a'; 
Huqinwei.age = 27; 
nbsp;Huqinwei.height = 185; 

In addition to the symbol ".", struct member variables can be accessed by "-" > "Visit (to be mentioned below).

References (C++), Pointers, and arrays:

The first is references and Pointers:


int main() 
{ 
    struct stuff Huqinwei; 
    struct stuff &ref = Huqinwei; 
    ref.age = 100; 
    printf("Huqinwei.age is %d\n",Huqinwei.age); 
    printf("ref.age is %d\n",ref.age); 
    struct stuff *ptr = &Huqinwei; 
    ptr->age = 200; 
    printf("Huqinwei.age is %d\n",Huqinwei.age); 
    printf("ptr->age is %d\n",Huqinwei.age); 
// Now that you've written it, add the pointer reference  
    struct stuff *&refToPtr = ptr; 
    refToPtr->age = 300; 
    printf("Huqinwei.age is %d\n",Huqinwei.age); 
    printf("refToPtr->age is %d\n",refToPtr->age); 
}

Correction: the initialization statement for the reference was miswritten and did not indicate that the reference was not in pure C (in this blog under the guise of C).

Reference is a unique mechanism of C++, which must be supported by the compiler. What is the essence of reference conversion to C

The structure is not immune, must have an array:


struct test{ 
    int a[3]; 
    int b; 
}; 
// In the case that an array and a variable exist simultaneously, the following methods are defined:  
    struct test student[3] =   {{{66,77,55},0}, 
                    {{44,65,33},0}, 
                    {{46,99,77},0}}; 
// In particular, it can be simplified to:  
    struct test student[3] =    {{66,77,55,0}, 
                    {44,65,33,0}, 
                    {46,99,77,0}}; 

Variable length structure

You can make an array longer


// Take the variable name directly Huqinwei 
struct stuff{ 
    char job[20]; 
    int age; 
    float height; 
}Huqinwei; 
0

The results


// Take the variable name directly Huqinwei 
struct stuff{ 
    char job[20]; 
    int age; 
    float height; 
}Huqinwei; 
1

The length of the structure itself is one int length (this int value is usually used to represent the length of the later array). The later array length is not counted, but the array can be used directly.

(it's a pointer, right? Pointers also take up length! This is not occupied! The principle is simple. This thing is just the tail of the array. malloc is creating a piece of continuous space. It shouldn't be a mechanism, it should be more like a technique.)

20160405 added:

An inelastic array cannot be defined as an elastic (flexible) variable in the form "char a[]"; the size must be specified.

Elastic array in the structure, the following form is allowed only 1:


// Take the variable name directly Huqinwei 
struct stuff{ 
    char job[20]; 
    int age; 
    float height; 
}Huqinwei; 
2

Reversing the order will make the b and a data overlap, which will not pass at compile time.


char b[] = "hell"; Also not line, C and C++ Can't) 

The absence of the integer variable a will make the whole structure length 0 again. compiler does not allow compilation! The difference is that C++ in fact allows empty structures in the form, in essence, it avoids empty structures and class objects through the mechanism, and automatically allocates a byte to the empty structure object (sizeof () returns 1) to facilitate object identification and avoid address overlap! So, C, if you have a free structure, define two (or 1 dozen, or just 1 array) variables (objects) for that structure, and the address is exactly the same! ·!!!!! Debugging to see the program run, these statements are in fact fart, there is no running at all, no practical significance, C does not support empty structures at all (or I don't think it will be useful in any situation)


// Take the variable name directly Huqinwei 
struct stuff{ 
    char job[20]; 
    int age; 
    float height; 
}Huqinwei; 
4

With the exception of C++, C++ does not allocate space to structures with elastic arrays (for fear of some kind of conflict with the lengthen structure mechanism, such as how to calculate the size) :


// Take the variable name directly Huqinwei 
struct stuff{ 
    char job[20]; 
    int age; 
    float height; 
}Huqinwei; 
5

In C++, the two are not the same, but the empty structure is "large" (sizeof() returns 1).

20160321 added:

This mechanism takes advantage of one very important feature - the difference between an array and a pointer! Arrays and Pointers are identical in many operations, but not in nature. Most intuitively, Pointers can be changed to point to, but arrays cannot, because each memory address occupied by an array is used to save variables or objects, while the memory address occupied by a pointer is used to save one address, and an array does not have a single structure to save the address to point to. 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, which is the target address pointed to, and since the array does not store the target address, it cannot change the point. If you try to force an address into an array, you're just saying that assigning a pointer to an array is not type-compatible.

Structure nesting:

There is nothing too unexpected about structure nesting, as long as it follows the 1 definite rule:


// Take the variable name directly Huqinwei 
struct stuff{ 
    char job[20]; 
    int age; 
    float height; 
}Huqinwei; 
6

In particular, you can define the structure B on one side, and use it on the other side:


// Take the variable name directly Huqinwei 
struct stuff{ 
    char job[20]; 
    int age; 
    float height; 
}Huqinwei; 
7

Usage and testing:


    a.b.c = 11; 
    printf("%d\n",a.b.c); 
    a.sb.c = 22; 
    printf("%d\n",a.sb.c); 

The result was correct.

However, if the nested struct B is declared within A and a corresponding object entity b is not defined, the size of this struct B is still not included in the struct A.

Structure and function:

About the pass-through, first of all:


// Take the variable name directly Huqinwei 
struct stuff{ 
    char job[20]; 
    int age; 
    float height; 
}Huqinwei; 
9

Using the int member variable in a structure as something like the ordinary int variable 1 is a no-brainer.

The other two are passing copies and Pointers:


//struct A Define the same  
// Two functions are set up and passed separately struct A The structure and its pointer.  
void func1(struct A a){ 
    printf("%d\n",a.b.c); 
} 
void func2(struct A* a){ 
    printf("%d\n",a->b.c); 
} 
main(){ 
    a.b.c = 112; 
    struct A * pa; 
    pa = &a; 
    func1(a); 
    func2(&a); 
    func2(pa); 
} 

Occupied memory space:

struct can't claim memory space when struct is defined, but if it's a struct variable, it can be allocated when declared -- the relationship between the two is like C++ class and object, which allocate memory (but strictly speaking, as a code block, does ".text "in the struct definition really take up no space? This, of course, is the subject of another category).

The size of the structure is usually (just usually) the sum of the size of the variables contained in the structure. The following is a printout of size of the above structure:


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

The result is no surprise, they are both 28: char array 20, int variable 4, floating point variable 4.

Here's what's unusual:

For the smaller members of the structure, it may be forced to align, resulting in empty space, which is related to the mechanism of reading memory for efficiency. Usually 32-bit machine according to the 4 byte alignment, less than when 4 bytes, there are less than 4 bytes in a row, can not but worry alignment, wait to round up the whole, plus 1 elements beyond 1 alignment position, began to adjust, such as 3 + 2 or 1 + 4, the latter requires other (under the structure of the body size is 8 bytes), more relevant example, not now.


struct s 
{ 
char a; 
short b; 
int c; 
} 

Accordingly, 64-bit machines are aligned in 8 bytes. However, alignment is not absolute. You can modify the alignment with #pragma pack(). If you change it to 1, the size of the structure is the sum of the actual size of the member variables.

Unlike the C++ class, a struct cannot initialize its internal variables.

Here is a sample of the error:


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

PS: the declaration of the structure should also be noted for its location and scope.

C++ has a slightly different structure variable declaration definition than C, which is more "object-oriented" stylized and less demanding.

If you are familiar with the common methods, you should pay attention to the common mistakes. See C language structure for common mistakes.


Related articles: