歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 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\n",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};
 
三、結構體數組的初始化

數組到快捷初始化,結構體到初始化都了解了,那麼結構體數組到初始化呢?就是以上兩種方法到組合。感興趣的朋友可以自己寫個小例子,這裡我就不說了,免的大家嫌我羅嗦。哈哈。

Copyright © Linux教程網 All Rights Reserved