cat writebug.cn/history

一个开发者的技术博客。

C语言零长数组

前言:计算机语言是编译器和程序员交流的依据和规范,GNU C是GCC特有的功能,在Linux内核中被广泛应用。

帮助文档:http://gcc.gnu.org/onlinedocs/gcc-4.6.2/gcc/C-Extensions.html#C-Extensions

int *p;
p=(int[]){99};
GCC 临时变量

1、零长数组

GNU C允许声明长度为零的数组,但它只能被用于结构体的最后一个成员。

举例,如清单1: 

#include 
#include 
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就是一个零长数组,在sizeof看来它所占的空间为零。

在ISO C99中,使用变长数组也可以实现同样的功能,如清单2:

#include 
#include 
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 < thislinelengthispan>
    printf("%c ", thisline.contents[i]);  
    printf("\n");  
return 0;  
}  

例子输出结果: 

sizeof(struct line) = 4  
sizeof(thisline) = 4  
1 2 3 4 5

变长数组是不完全数据类型,不能使用sizeof获得它的大小。

注意,此结构体的变量必须在函数外定义和初始化,否则会报错: 

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、变长数组

在支持变长数组之前,C语言数组的大小是在声明时确定的(下标是一个常量表达式)并一直保持不变。所谓变长数组就是指数组的大小可以在运行时指定,如清单3: 

#include 
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 //输入数字6
sizeof(arr[9]) = 36 //输入数字9
    输入不同的值,数组的大小随之改变。

变长数组作为参数进行传递的例子,如清单4: 

#include 
int sum(int num, int arr[num])  
{  
int i, total = 0;  
for (i = 0; i < numispan>
    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  
    函数sum形参中的arr可以匹配任意的一维整型数组。
    注意,num一定要声明在变长数组arr之前。