前言:計算機語言是編譯器和程序員交流的依據(jù)和規(guī)范,GNU C是GCC特有的功能,在Linux內(nèi)核中被廣泛應用。
幫助文檔:http://gcc./onlinedocs/gcc-4.6.2/gcc/C-Extensions.html#C-Extensions
1、零長數(shù)組
GNU C允許聲明長度為零的數(shù)組,但它只能被用于結構體的最后一個成員。
舉例,如清單1:
- #include <stdio.h>
- #include <stdlib.h>
-
- struct line {
- int length;
- char contents[0];
- };
-
- int main(void)
- {
- int i, count = 9;
- char letter = 'A';
-
- struct line *thisline = (struct line *)malloc(sizeof(struct line) + count);
-
- thisline->length = count;
- for (i = 0; i < count; i++)
- thisline->contents[i] = letter++;
-
- printf("sizeof(struct line) = %d\n", sizeof(struct line));
-
- for (i = 0; i < thisline->length; i++)
- printf("%c ", thisline->contents[i]);
- printf("\n");
-
- return 0;
- }
例子輸出結果:
- sizeof(struct line) = 4
- A B C D E F G H I
如例子中的第6行,contents就是一個零長數(shù)組,在sizeof看來它所占的空間為零。
在ISO C99中,使用變長數(shù)組也可以實現(xiàn)同樣的功能,如清單2:
- #include <stdio.h>
- #include <stdlib.h>
-
- struct line {
- int length;
- char contents[];
- };
-
- struct line thisline = { 5, {'1', '2', '3', '4', '5' } };
-
- int main(void)
- {
- int i;
-
- printf("sizeof(struct line) = %d\n", sizeof(struct line));
- printf("sizeof(thisline) = %d\n", sizeof(thisline));
-
- for (i = 0; i < thisline.length; i++)
- printf("%c ", thisline.contents[i]);
- printf("\n");
-
- return 0;
- }
例子輸出結果:
- sizeof(struct line) = 4
- sizeof(thisline) = 4
- 1 2 3 4 5
變長數(shù)組是不完全數(shù)據(jù)類型,不能使用sizeof獲得它的大小。
注意,此結構體的變量必須在函數(shù)外定義和初始化,否則會報錯:
- error: non-static initialization of a flexible array member
- error: (near initialization for 'thisline')
不能使用這樣的形式:
- struct mystruct {
- int arr[];
- };
否則會報錯:
- error: flexible array member in otherwise empty struct
2、變長數(shù)組
在支持變長數(shù)組之前,C語言數(shù)組的大小是在聲明時確定的(下標是一個常量表達式)并一直保持不變。所謂變長數(shù)組就是指數(shù)組的大小可以在運行時指定,如清單3:
- #include <stdio.h>
-
- int main(void)
- {
- int i;
-
- scanf("%d", &i);
-
- int arr[i];
-
- printf("sizeof(arr[%d]) = %d\n", i, sizeof(arr));
-
- return 0;
- }
例子輸出結果:
- sizeof(arr[6]) = 24
-
- sizeof(arr[9]) = 36
輸入不同的值,數(shù)組的大小隨之改變。
變長數(shù)組作為參數(shù)進行傳遞的例子,如清單4:
- #include <stdio.h>
-
- int sum(int num, int arr[num])
- {
- int i, total = 0;
-
- for (i = 0; i < num; i++)
- total += arr[i];
-
- return total;
- }
-
- int main(void)
- {
- int a[] = {1, 2, 3, 4};
- int b[] = {5, 6, 7, 8, 9, 10};
-
- printf("a[] total value: %d\n", sum(sizeof(a)/sizeof(a[0]), a));
- printf("b[] total value: %d\n", sum(sizeof(b)/sizeof(b[0]), b));
-
- return 0;
- }
例子輸出結果:
- a[] total value: 10
- b[] total value: 45
函數(shù)sum形參中的arr可以匹配任意的一維整型數(shù)組。
注意,num一定要聲明在變長數(shù)組arr之前