C語言結構體數組同時賦值的另類用法

說到C語言結構體數組的同時賦值,許多人一想就會想到用如下的這種方法,我們來寫一個例子:數組

#include <stdio.h>
struct student
{
	int a; 
	int b ; 
	int c ; 
};
struct student array1[1000] ;
int main(void)
{
	int i ;
	for(i = 0 ; i < 1000 ; i++)
	{
		array[i].a = 1 ;
		array[i].b = 2 ;
		array[i].c = 3 ;
	}
	for(i = 0 ; i < 1000 ; i++)
	{
		printf("array[%d].a:%d array[%d].b:%d array[%d].c:%d \n"  ,
		i, array[i].a ,i, array[i].b ,i, array[i].c);
	}
	return 0 ;
}
運行結果:

這樣就能夠實現對結構體數組同時賦值了。spa


閱讀Linux內核源代碼的時候看到了,原來C語言還有一種更少人知道的方法,使用 "..." 的形式,這種形式是指第幾個元素到第幾個元素,都是同樣的內容。這種用法在標準C上也是容許的,沒有語法錯誤,咱們來看看它是怎麼用的:.net

#include <stdio.h>
struct student
{
	int a; 
	int b ; 
	int c ; 
};
//對第0個數組到第999個結構體數組同時賦值同樣的內容 
struct student array[1000] = {
	[0 ... 999] = {
	.a = 1 ,
	.b = 2 ,
	.c = 3 ,
	}
};

int main(void)
{
	int i ; 
	//輸出賦值後的數值 
	for(i = 0 ; i < 1000 ; i++)
	{
		printf("array[%d].a:%d array[%d].b:%d array[%d].c:%d \n"  ,
		i, array[i].a ,i, array[i].b ,i, array[i].c);
	}
	return 0 ;
}
運行結果:





本文同步分享在 博客「Engineer-Bruce_Yang」(CSDN)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。code

相關文章
相關標籤/搜索