看如下代码:
#include<stdio.h> typedef struct { int len; int array[]; }SoftArray; int main() { int len = 10; printf("The struct's size is %d\n",sizeof(SoftArray)); return 0; }
运行结果:
[root@VM-0-7-centos mydoc]# ./a.out
The struct's size is 4
我们可以看出,_SoftArray结构体的大小是4,显然,在32位操作系统下一个int型变量大小刚好为4,也就说结构体中的数组没有占用内存。为什么会没有占用内
存,我们平时用数组时不时都要明确指明数组大小的吗?但这里却可以编译通过呢?这就是我们常说的动态数组,也就是变长数组。
先不要乱,让我们再看一段代码
#include<stdio.h> #include<malloc.h> typedef struct { int len; int array[]; }SoftArray; int main() { int len = 10; SoftArray *p=(SoftArray*)malloc(sizeof(SoftArray) + sizeof(int)*len); printf("SoftArray size is %d\n", sizeof(SoftArray)); free(p); return 0; }
运行结果:
[root@VM-0-7-centos mydoc]# ./a.out
SoftArray size is 4<