# 指定初始化器的概念

C90 标准要求初始化程序中的元素以固定的顺序出现，与要初始化的数组或结构体中的元素顺序相同。但是在新标准 C99 中，增加了一个新的特性：指定初始化器。利用该特性可以初始化指定的数组或者结构体元素。

## 数组的指定初始化器

### 一维数组的指定初始化器

int a[6] = {[4] = 10,[2] = 25};


int a[6] = {0,0,25,0,10,0};


int a[5] = {[4] = 10,[0 ... 3] = 23};


int a[5] = {23,23,23,23,10};


int a[5] = {11,[3] = 44,55,[1] = 22,33};


int a[5] = {11,22,33,44,55};


int main(void)
{
int number[] = {[20] = 1,[10] = 8,9};
int n = sizeof(number)/sizeof(number[0]);
printf("The Value of n is:%d\n",n);
}


The Value of n is:21


### 二维数组的指定初始化器

int array[2][2] =
{
[0] = {[0] = 11},
[1] = {[1] = 22},
};


int array1[2][2] =
{
{11,00},
{00,22}
};


### 应用

typedef enum
{
Idle_State,
Card_Inserted_State,
Pin_Entered_State,
Option_Selected_State,
Amount_Entered_State,
last_State
}eSysyemState;

typedef enum
{
Card_Insert_Event,
Pin_Enter_Event,
Option_Selection_Event,
Amount_Enter_Event,
Amount_Dispatch_Event,
last_Event
}eSystemEvent;


eSysyemState AmountDispatchHandler(void)
{
return Idle_State;
}

eSysyemState EnterAmountHandler(void)
{
return Amount_Entered_State;
}

eSysyemState OptionSelectionHandler(void)
{
return Option_Selected_State;
}

eSysyemState InsertCardHandle(void)
{
return Card_Inserted_State;
}

eSysyemState EnterPinHandler(void)
{
return Pin_Entered_State;
}


typedef eSysyemState (* const afEventHandler[last_State][last_Event])(void);


typedef int array[3];
array data;


int data[3];


    static afEventHandler StateMachine =
{
[Idle_State] = {[Card_Insert_Event] = InsertCardHandle},
[Card_Inserted_State] = {[Pin_Enter_Event] = EnterPinHandler },
[Pin_Entered_State] = {[Option_Selection_Event] = OptionSelectionHandler},
[Option_Selected_State] = {[Amount_Entered_Event] = EnterAmountHandler},
[Amount_Entered_State] = {[Amount_Dispatch_Event] = AmountDispatchHandler},
};


#include <stdio.h>

int main(void)
{
eSysyemState eNextState = Idle_State;
eSystemEvent eNewEvent;
while(1)
{
/*省略相关判断*/
eNextState = (*StateMachine[eNextState][eNewEvent])();
}
return 0;
}


## 结构体的指定初始化器

struct point
{
int x,y;
}


struct point p =
{
.y = 2,
.x = 3
};


struct point p = {3,2};


const struct file_operations eeprom_fops =
{
.llseek  = eeprom_lseek,
.write   = eeprom_write,
.open    = eeprom_open,
.release = eeprom_close
};


struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
int (*open) (struct inode *, struct file *);
int (*flush) (struct file *, fl_owner_t id);
int (*release) (struct inode *, struct file *);
/*还有很多，省略*/
}


## 结构体数组的指定初始化器

#include <stdio.h>
int main(void)
{
struct point {int x,y;};
struct point pts[5] =
{
[2].y = 5,
[2].x = 6,
[0].x = 2
};
int i;
for(i = 0;i < 5;i++)
printf("%d %d\n",pts[i].x,pts[i].y);
}


2 0
0 0
6 5
0 0
0 0


# 总结

posted @ 2020-04-28 11:19  wenzid  阅读(474)  评论(2编辑  收藏  举报