C language, structure, structure size,

      1. Structure:

        Used to store multiple related variables of different data types to form an independent composite data type.

The declaration of the structure:

struct structure type name {

      datatype member 1;

      datatype member 2;

      datatype member 3;

………

} ; // Note the semicolon here

Declaration: Create a custom data type, this type is called <struct structure type name> è data type;

      struct student(){

      char name[32];

      int age;

      char sex;

      double score;

}

struct student è customize a data type

Define structure variables:

      struct studet  structure variable name;

      struct studies stu;

initialization:

      struct student stu ={ “zhangsan”,18 ,’M’,88.8};

use:

      Structure variable name. Member name: -->  array name [subscript]

      stu.age -->18;

assignment:

      When assigning values ​​to the structure content, you can only assign values ​​one by one.

      But you can directly assign values ​​between structures of the same type.

Structure pointer:

      struct student *p;

      Use pointers to get data

      (*p).sex -->    'm' // basically not used

      p->sex --> ' m' // use this

/*===============================================
*   文件名称:struct_KT.c
*   创 建 者:WM
*   创建日期:2023年08月15日
*   描    述:结构体基础知识
================================================*/
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
typedef struct student
{
    char name[32];
    int age;
    char sex;
    double score;
}stu,*pstu;

int main(int argc, char *argv[])
{
   // stu s1={"zhangsan",18,'m',88.8},s2;
    //s2=s1;
    // strcpy(s2.name,"lisi");
    // s2.age=19;
    // s2.sex='w';
    // s2.score=29.0;
    stu s3;
    scanf("%s",s3.name);
    scanf("%d",&s3.age);
    //scanf("%*c%c",&s3.sex);//方法1、去除脏字字符'\r'回车
    getchar(); //方法2、去除脏字字符'\r'回车,放在输入数据之前
    scanf("%c",&s3.sex);
    
    scanf("%lf",&s3.score);

    //结构体指针
    pstu p=&s3;
    printf("%s,%d,%c,%.2lf\n",s3.name,s3.age,s3.sex,s3.score);
    printf("%c\n",p->sex);

    pstu k=(struct student *)malloc(sizeof(stu));
    strcpy(k->name,"wangwu");
    puts(k->name);
    free(k);
    return 0;
} 

2. Structure size:

  1. Aligned using the length of the largest data type in the structure members . A member will not be assigned to multiple grids.
  2. Alignment operations start from top to bottom. It will only be placed in a position that is a multiple of the size of its own data type.
  3. An array is equivalent to writing a bunch of variables of the corresponding type.

      

1111

1011

1000

so for 12

1111 1111

1111 1111

1111 1110

1100 0000

1111 1111

so for 40

Guess you like

Origin blog.csdn.net/qq_52119661/article/details/132303398