- Common construction types:
- Arrays, structures, unions;
- The role of the structure:
- Structures can be used to manage data of different data types;
- Pseudocode says:
struct 类型名{
数据类型1 成员1;
数据类型2 成员2;
数据类型3 成员3;
.
.
.
数据类型n 成员n;
};
- Features of the structure:
- All members are variables;
- Members are separated by semicolons;
- The storage of members in the memory space is continuous;
- Structure variables can be directly assigned to each other;
- Define the format of structure variables and structure arrays:
struct 结构体类型名 结构体变量名;
struct 结构体类型名 结构体数组名[下标];
- The format of structure access members:
结构体变量名.成员名;
结构体指针->成员名;
#include <stdio.h>
#include <stdlib.h>
#define N 5
typedef struct K_Data
{
short a;
int b;
char *s;
int k[N];
}my_data;
int main(int argc, char const *argv[])
{
struct K_Data k1;
my_data k2;
k1.a = 99;
k2.b = 100;
printf("k1.a = %d,k2.b = %d\n",k1.a,k2.b);
puts("----------------------------------------------------------");
my_data k3;
k3.s = "ABAB";
printf("%s\n",k3.s);
puts("----------------------------------------------------------");
my_data k4;
k4.k[0] = 1;
k4.k[1] = 2;
k4.k[2] = 3;
k4.k[3] = 4;
k4.k[4] = 5;
for(int i = 0; i < N; i++){
printf("k4.k[%d] = %d ",i,k4.k[i]);
}
puts("");
puts("----------------------------------------------------------");
struct K_Data *k5 = (struct K_Data *)malloc(sizeof(struct K_Data));
printf("k5 = %p\n",k5);
k5->a = 666;
printf("k5->a = %d\n",k5->a);
free(k5);
k5 = NULL;
printf("k5 = %p\n",k5);
puts("----------------------------------------------------------");
my_data *k6 = (my_data *)malloc(sizeof(my_data));
printf("k6 = %p\n",k6);
k6->a = 999;
printf("k6->a = %d\n",k6->a);
free(k6);
k6 = NULL;
printf("k6 = %p\n",k6);
puts("----------------------------------------------------------");
struct K_Data *k7 = &k1;
k7->a = 555;
printf("k7->a = %d\n",k7->a);
return 0;
}
k1.a = 99,k2.b = 100
----------------------------------------------------------
ABAB
----------------------------------------------------------
k4.k[0] = 1 k4.k[1] = 2 k4.k[2] = 3 k4.k[3] = 4 k4.k[4] = 5
----------------------------------------------------------
k5 = 0x55877264c670
k5->a = 666
k5 = (nil)
----------------------------------------------------------
k6 = 0x55877264c670
k6->a = 999
k6 = (nil)
----------------------------------------------------------
k7->a = 555