C99 指定初始化

C99新特性,允许对数组元素或结构体元素的特定成员进行初始化而不用按顺序进行初始化。

如:

struct S1 {
    int i;
    float f;
    int a[2];
};
struct S1 x = {
   .f=3.1,
   .i=2,
   .a[1]=9
};
下面那个结构体的定义就对指定的成员进行初始化,指定成员时,如果是单个变量则用"."点指定,如果是数组元素,则用"[常量表达式]"指定,这两者可以混用。

下面的列子中,所有的数组都被始化为了相同的值。

	struct S2 {
		int x, y;
	};
	// Arrays a1, a2, a3, a4, and a5 are
	// initialized to the same values.
	struct S2 a1[3] = {1, 2, 3, 4, 5, 6};
	struct S2 a2[3] =
	{
		{1, 2},
		{3, 4},
		5, 6
	};
	struct S2 a3[3] =
	{
		[2].y=6, [2].x=5,
		[1].y=4, [1].x=3,
		[0].y=2, [0].x=1
	};
	struct S2 a4[3] =
	{
		// Current object is all of a4
		[0].x=1, [0].y=2,
		{
			// Current object is a4[1]
			x=3, .y=4
		}
		// Current object is all of a4
		// Current position is [2]
		5, [2].y=6
	};
	struct S2 a5[3] =
	{
		// After [2].x follows [2].y
		[2].x=5, 6,
		// After [0].x follows [0].y
		[0].x=1, 2,
		// after [0].y is [1]
		3, 4
	};
	struct S2 a6[3] =
	{
		// Current object is all of a4
		[0].x=1, [0].y=2,
		[1] = {
			// Current object is a4[1]
			x=3, .y=4
		}
		// Current object is all of a4
		// Current position is [2]
		5, [2].y=6
	};

 
 
double a7[3][3] ={[0][0]=1, [1][1]=1, [2][2]=1}; //矩阵a7除了主对角线初始化为1外,其它的都初始化为0


你可能感兴趣的:(C99 指定初始化)