GCC 中零长数组,C99中的变长数组(VLA)
GCC 中零长数组
GCC 中允许使用零长数组,把它作为结构体的最后一个元素非常有用,下面例子出自 gcc 官方文档。
struct line {
int length;
char contents[0];
};
struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length);
thisline->length = this_length;
C99中的变长数组
1 #include<stdio.h>
2
3 #define ROWS 3
4 #define COLS 4
5
6 int sum2d(int rows, int cols, int ar[rows][cols])
7 {
8 int i, j, sum;
9 sum = 0;
10
11 for(i = 0; i < rows; i++)
12 for(j = 0; j < cols; j++)
13 sum += ar[i][j];
14 return sum;
15 }
16
17 int main()
18 {
19 int i, j;
20 int junk[ROWS][COLS] = {
21 {2, 4, 6, 8},
22 {3, 5, 7, 9},
23 {12, 10, 8, 6}
24 };
25
26 int morejunk[ROWS-1][COLS+2] = {
27 {20, 30, 40, 50, 60, 70},
28 {5, 6, 7, 8, 9, 10}
29 };
30 int rs = ROWS;
int cs = COLS;
31 int varr[rs][cs]; //变长数组
32
33 for(i = 0; i < rs; i++)
34 for(j = 0; j < cs; j++)
35 varr[i][j] = i * j +j;
36 printf("3 * 5 array\n");
37 printf("sum of all elemts = %d\n",sum2d(ROWS, COLS, junk));
38
39 printf("2 * 6 array\n");
40 printf("sum of all elemts = %d\n",sum2d(ROWS - 1, COLS + 2, morejunk));
41
42 printf("3 * 10 array\n");
43 printf("sum of all elemts = %d\n",sum2d(rs, cs, varr));
44
45 return 0;
46 }