C语言学习之初识结构体

  • 常见的构造类型:
  • 数组、结构体、共用体;
  • 结构体的作用:
  • 可以使用结构体管理不同数据类型的数据;
  • 伪代码表示:
struct 类型名{
	数据类型1 成员1;
	数据类型2 成员2;
	数据类型3 成员3;
	.
	.
	.
	数据类型n 成员n;
};
  • 结构体的特点:
  • 所有的成员都是变量;
  • 成员之间用分号隔开;
  • 成员在内存空间的存储是连续的;
  • 结构体变量之间是可以直接相互赋值的;
  • 定义结构体变量和结构体数组的格式:
	struct 结构体类型名 结构体变量名;
	struct 结构体类型名 结构体数组名[下标];
  • 结构体访问成员的格式:
	结构体变量名.成员名;
	结构体指针->成员名;
  • 示例代码:
#include 
#include 
#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

你可能感兴趣的:(C语言学习系列,c语言,学习,开发语言,linux,运维)