Welcome 微信登录

首页 / 操作系统 / Linux / Linux中数组与结构体的快捷初始化

最近看了linux内核的一点代码,感受颇深,由于自己知识的匮乏,有些用法以前都没有见过,现在就把数组和结构体初始化的部分简单的记录一下。那么怎么快捷方便的对数组和结构体进行初始化呢?一、数组快捷初始化
      我们使用的方法有这么几种:
      (1) int an_temp[10] = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};    //初始化成指定数据到数组
       或者
      (2)int an_temp[10]; memset(an_temp,0,sizeof(int)*10); //数组清零
      果如数组到长度是128或者更大呢?对于方法二还是可以接受的,若使用方法一把数组初始化成指定内容该怎么办?用循环?有其他方法吗?还有其他方法吗?那么我们就来说一下:
  
      int an_temp[128] = {[0 ... 127] = -1};      对,你们没有看错,就是这样,简单吧!www.linuxidc.com 有兴趣到朋友可以做个简单到例子。      #include <stdio.h>
      int main()
      {
          int an_temp[128] = {[0 ... 127] = -2};
          int i = 0;
 
          for(i=0;i<128;i++)
              printf("%d ",an_temp[i]);
 
          return 0;
      }二、结构体的初始化
      我们用以下结构体为例子:
      struct struct_temp
       {
          int dd;
          int cc[128];
       };
 
      我们平常到初始化是这个样子的:
      (1) struct struct_temp st_temp;
          memset(&struct_temp,0,sizeof(struct struct_temp));
       或者
      (2)struct struct_temp st_temp;
         st_temp.dd = -1;
         int i =0;
         for(i=0;i<128;i++)
         st_temp.cc[i] = -1;      对于第二种方法,有没有更方便到呢?当然有,如下:
      struct struct_temp st_temp = {.dd=-1, .cc[0 ... 127] = -2};
      这种方法我们都可以调换初始化的顺序,如下:
      struct struct_temp st_temp = {.cc[0 ... 127] = -2, .dd=-1};
 
三、结构体数组的初始化数组到快捷初始化,结构体到初始化都了解了,那么结构体数组到初始化呢?就是以上两种方法到组合。感兴趣的朋友可以自己写个小例子,这里我就不说了,免的大家嫌我罗嗦。哈哈。Linux做NAT服务和端口映射的命令Ubuntu搭建Qt开发环境相关资讯      Linux内核开发 
  • Who Writes Linux 2015  (06/05/2015 19:37:38)
  • Linux内核开发:container_of分析  (01/17/2013 18:53:35)
  • Linux之DMA API -- 通用设备的动态  (09/03/2012 06:27:04)
  • Linux内核开发:offset宏的讲解  (01/17/2013 18:55:41)
  • Linux 进程调度  (09/13/2012 10:07:08)
  • Linux之DMA动态映射指南  (09/03/2012 06:21:49)
本文评论 查看全部评论 (0)
表情: 姓名: 字数