Structures and unions

C language structure is somewhat similar to the object, but can not inherit instantiated, can only be used to represent different types of data storage.

For example, a top Book "object":

struct Book{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;    
} book;

Book which is a variable name tag structure, book structure, inside the char title [50]; is a definition of a variable.

==========================================================

char title [50]; 50 represents the space character lives on the title variable mandatory.

In the C language, strings are actually using the  null  character '\ 0' one-dimensional array of characters terminated, for example, I want to print a hello, this is a total of five characters in it,

char the Greeting [] = "the Hello" ; // Finally, the compiler will automatically add an If: char the Greeting [5] = "the Hello"; this is an exception will be displayed  

 char greeting [4] = "hello"; prompts length is too small.

===========================================================

Member method of accessing structure: using (dot) to access the object using properties and closer.

Defined the structure after declaring variables ---> can be compared, define the class in the future, the object is instantiated

struct Book book1;
struct Book book2;

 

Memory alignment:

Alignment more generally divided into four eight-byte alignment and byte alignment, that particular way to structure the maximum byte length prevail, as the pointer is 8 bytes, eight bytes places subject, if only char, int int length prevail places 4 bytes, if a structure which has three full char, then that is a byte alignment.

System 32 is 4 bytes long; 64-bit system is 8 bytes long

have a test

book.c

#include <stdio.h>
struct Book{
       char title;
       int i;      
} book;
int main (){
    struct Book book;
     printf("%zu",sizeof(book));
}

Compile and run:

gcc  book.c

./a.out

 

========================================================================================================================================

Union:


Union name suggests, is a shared memory, or different types of variables stored in the same location. To define a union member with a plurality, but at any time only one member with the value. Like the toilet, you can go to different people, but each time only one person.

It has a maximum size of a union decision.

have a test:

 

#include <stdio.h>
 
union Data
{
   int i;
   float f;
   char  u[20];
} data;
 
int main( )
{
   union Data data;        
 
   printf( "%d\n", sizeof(data));
 
   return 0;
}

 

Guess you like

Origin www.cnblogs.com/callmelx/p/11011632.html